package sdk.webview.fmc.com.fmcsdk.activity;

import static sdk.webview.fmc.com.fmcsdk.app.AppManager.getAppManager;

import android.Manifest;
import android.annotation.SuppressLint;
import android.app.ActivityManager;
import android.app.AlertDialog;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.pm.ActivityInfo;
import android.content.pm.PackageManager;
import android.content.res.Configuration;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.graphics.BitmapFactory;
import android.graphics.PixelFormat;
import android.media.MediaMetadataRetriever;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.net.Uri;
import android.net.wifi.WifiInfo;
import android.net.wifi.WifiManager;
import android.os.Build;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.os.Message;
import android.os.PowerManager;
import android.preference.PreferenceManager;
import android.provider.MediaStore;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.ContextCompat;
import android.support.v4.content.FileProvider;
import android.telephony.PhoneStateListener;
import android.telephony.ServiceState;
import android.telephony.SignalStrength;
import android.telephony.TelephonyManager;
import android.text.TextUtils;
import android.util.Log;
import android.view.KeyEvent;
import android.view.MotionEvent;
import android.view.View;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.EditText;
import android.widget.FrameLayout;
import android.widget.LinearLayout;
import android.support.design.widget.Snackbar;

import com.baidu.location.BDAbstractLocationListener;
import com.baidu.location.BDLocation;
import com.baidu.location.LocationClient;
import com.baidu.location.LocationClientOption;
import com.baidu.mapapi.model.LatLng;
import com.baidu.mapapi.search.core.PoiInfo;
import com.baidu.mapapi.search.core.SearchResult;
import com.baidu.mapapi.search.geocode.GeoCodeResult;
import com.baidu.mapapi.search.geocode.GeoCoder;
import com.baidu.mapapi.search.geocode.OnGetGeoCoderResultListener;
import com.baidu.mapapi.search.geocode.ReverseGeoCodeOption;
import com.baidu.mapapi.search.geocode.ReverseGeoCodeResult;
import com.google.gson.Gson;
import com.tencent.smtt.export.external.interfaces.IX5WebChromeClient;
import com.tencent.smtt.export.external.interfaces.WebResourceRequest;
import com.tencent.smtt.sdk.ValueCallback;
import com.tencent.smtt.sdk.WebSettings;
import com.tencent.smtt.sdk.WebView;
import com.tencent.smtt.sdk.WebViewClient;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.File;
import java.io.Serializable;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;

import cn.jpush.android.api.JPushInterface;
import sdk.webview.fmc.com.fmcsdk.BaoTipEvent;
import sdk.webview.fmc.com.fmcsdk.R;
import sdk.webview.fmc.com.fmcsdk.app.AppManager;
import sdk.webview.fmc.com.fmcsdk.app.FMCApplication;
import sdk.webview.fmc.com.fmcsdk.base.BaseActivity;
import sdk.webview.fmc.com.fmcsdk.base.BindEventBus;
import sdk.webview.fmc.com.fmcsdk.bean.CaUploadImage;
import sdk.webview.fmc.com.fmcsdk.bean.DDTypeBean;
import sdk.webview.fmc.com.fmcsdk.bean.GETREPORTBean;
import sdk.webview.fmc.com.fmcsdk.bean.GPSBean;
import sdk.webview.fmc.com.fmcsdk.bean.ImageNameId;
import sdk.webview.fmc.com.fmcsdk.bean.NFCResult;
import sdk.webview.fmc.com.fmcsdk.bean.NoNetImageBean;
import sdk.webview.fmc.com.fmcsdk.bean.NotificationSound;
import sdk.webview.fmc.com.fmcsdk.bean.NotificationUpdateTaskList;
import sdk.webview.fmc.com.fmcsdk.bean.OpenMessageEvent;
import sdk.webview.fmc.com.fmcsdk.bean.PhotoUploadBean;
import sdk.webview.fmc.com.fmcsdk.bean.RecordError;
import sdk.webview.fmc.com.fmcsdk.bean.StartPauseBean;
import sdk.webview.fmc.com.fmcsdk.bean.SubMitPointBean;
import sdk.webview.fmc.com.fmcsdk.bean.SysKesDescBean;
import sdk.webview.fmc.com.fmcsdk.bean.SystemSetting;
import sdk.webview.fmc.com.fmcsdk.bean.UploadHandlerBean;
import sdk.webview.fmc.com.fmcsdk.bean.UploadImage;
import sdk.webview.fmc.com.fmcsdk.bean.UploadImageBean;
import sdk.webview.fmc.com.fmcsdk.bean.UploadVideDataBean;
import sdk.webview.fmc.com.fmcsdk.bean.WorkOrderNumBean;
import sdk.webview.fmc.com.fmcsdk.camera.BitmapUtils;
import sdk.webview.fmc.com.fmcsdk.check.CacheHelper;
import sdk.webview.fmc.com.fmcsdk.check.EventBusWork;
import sdk.webview.fmc.com.fmcsdk.check.activity.CheckDetailsActivity;
import sdk.webview.fmc.com.fmcsdk.check.activity.StartWorkActivity;
import sdk.webview.fmc.com.fmcsdk.check.bean.GetDetailsBean;
import sdk.webview.fmc.com.fmcsdk.check.bean.WorkHistoryBean;
import sdk.webview.fmc.com.fmcsdk.check.listener.StartH5Event;
import sdk.webview.fmc.com.fmcsdk.db.DBManager;
import sdk.webview.fmc.com.fmcsdk.db.DatabaseManager;
import sdk.webview.fmc.com.fmcsdk.db.IMAGE;
import sdk.webview.fmc.com.fmcsdk.db.Record;
import sdk.webview.fmc.com.fmcsdk.db.VIDEO;
import sdk.webview.fmc.com.fmcsdk.h5.H5Presenter;
import sdk.webview.fmc.com.fmcsdk.h5.H5View;
import sdk.webview.fmc.com.fmcsdk.h5.H5WebViewClient;
import sdk.webview.fmc.com.fmcsdk.h5.JsInterface;
import sdk.webview.fmc.com.fmcsdk.h5.X5WebView;
import sdk.webview.fmc.com.fmcsdk.imagepicker.utils.Utils;
import sdk.webview.fmc.com.fmcsdk.interfaces.OnDialogStringListener;
import sdk.webview.fmc.com.fmcsdk.record.util.ScreenUtils;
import sdk.webview.fmc.com.fmcsdk.imagepicker.ImagePicker;
import sdk.webview.fmc.com.fmcsdk.imagepicker.bean.MediaFile;
import sdk.webview.fmc.com.fmcsdk.imagepicker.loader.GlideLoader;
import sdk.webview.fmc.com.fmcsdk.imagepicker.manager.ConfigManager;
import sdk.webview.fmc.com.fmcsdk.service.LocationService;
import sdk.webview.fmc.com.fmcsdk.service.NetworkListEvent;
import sdk.webview.fmc.com.fmcsdk.service.NetworkListenerService;
import sdk.webview.fmc.com.fmcsdk.service.UploadEventLoad;
import sdk.webview.fmc.com.fmcsdk.service.UploadFileManager;
import sdk.webview.fmc.com.fmcsdk.service.UploadImageService;
import sdk.webview.fmc.com.fmcsdk.upload.ImageUploadBean;
import sdk.webview.fmc.com.fmcsdk.util.Constant;
import sdk.webview.fmc.com.fmcsdk.util.DownloadFileManager;
import sdk.webview.fmc.com.fmcsdk.util.FastClickHelper;
import sdk.webview.fmc.com.fmcsdk.util.FileUtil;
import sdk.webview.fmc.com.fmcsdk.util.GsonUtil;
import sdk.webview.fmc.com.fmcsdk.util.HandleJsEvent;
import sdk.webview.fmc.com.fmcsdk.util.ImageUtils;
//import sdk.webview.fmc.com.fmcsdk.util.JpushUtils;
//import sdk.webview.fmc.com.fmcsdk.util.JpushUtils;
import sdk.webview.fmc.com.fmcsdk.util.KLog;
import sdk.webview.fmc.com.fmcsdk.util.NetworkUtils;
import sdk.webview.fmc.com.fmcsdk.util.PasswordUtils;
import sdk.webview.fmc.com.fmcsdk.util.PreferencesHelper;
import sdk.webview.fmc.com.fmcsdk.util.SharedPrefUtils;
import sdk.webview.fmc.com.fmcsdk.util.SnackBarUtil;
import sdk.webview.fmc.com.fmcsdk.util.SoundUtils;
import sdk.webview.fmc.com.fmcsdk.util.TitleBar;
import sdk.webview.fmc.com.fmcsdk.util.ToastUtils;
import sdk.webview.fmc.com.fmcsdk.util.Url;
import sdk.webview.fmc.com.fmcsdk.util.UserHelper;
import sdk.webview.fmc.com.fmcsdk.util.Util;
import sdk.webview.fmc.com.fmcsdk.util.Utility;
import sdk.webview.fmc.com.fmcsdk.util.XLog;
import sdk.webview.fmc.com.fmcsdk.util.retrofit2.subscriber.RxBus;
import sdk.webview.fmc.com.fmcsdk.util.retrofit2.subscriber.RxBusSubscriber;
import sdk.webview.fmc.com.fmcsdk.view.AvatarSelectDialog;
import sdk.webview.fmc.com.fmcsdk.view.ChangePasswordDialog;
import sdk.webview.fmc.com.fmcsdk.view.GPSCustomDialog;
import sdk.webview.fmc.com.fmcsdk.view.NoticeTipsDialog;
import sdk.webview.fmc.com.fmcsdk.view.ShowMediaDialog;


/**
 * 加载H5页面。
 */
@BindEventBus
public class H5Activity extends BaseActivity<H5View, H5Presenter> implements H5WebViewClient.OnReceivedErrorListener, JsInterface.HtmlInterface, H5View {


    FrameLayout webFramlayout;
    TitleBar titlebar;
    LinearLayout llSearch;
    EditText edittextSearch;
    Button btSearch;
    Button btSave;
    public static X5WebView webView;
    private static final int SCAN_CODE = 9;
    public static final int TAKEPIC_H5 = 14;
    public static final int RECORDVIDEO_H5 = 15;
    public static final int ABLUM_VIDEO = 16;
    private static final int IMAGEEDIT_OK = 19;
    private static final int OPEN_ABLUM = 24;
    /**
     * H5操作后给handler发送的标识
     */
    private static final int MSG_INIT_UI = 110;
    private static final int SHOW_DIALOG = 111;
    private static final int HIDE_DIALOG = 112;
    private static final int TAKEPIC_SUCCESS = 113;
    private static final int TAKEPHOTO_EDITIMAGE_SUCCESS = 114;
    private static final int SCAN_SUCCESS = 115;
    private static final int TAKEPIC_UPLOAD = 116;
    private static final int TAKEPIC_UPLOAD_ALL = 1116; //多选用这个
    private static final int TAKEPIC_FOR_URL_SUCCESS = 117;
    private static final int GET_ACCESSTOKEN_SUCCESS = 118;
    private static final int ONKEYDOWN_SUCCESS = 119;
    private static final int NETWORK_ONLINE = 120;
    private static final int NETWORK_OFFLINE = 127;
    private static final int ONE_CLICK = 121;
    private static final int DOUBLE_CLICK = 122;
    private static final int CLEAR_STORAGE = 123;
    private static final int SET_CURRENT_LANGUAGE = 124;
    private static final int SAVE_H5DATA_TO_LOCAL = 125;
    private static final int GET_H5DATA_FOR_LOCAL = 126;
    private static final int RELOAD_URL = 128;
    private static final int GET_LOCATION_SUCCESS = 129;
    private static final int INIT_CALLBACK_HTMLT_RESULT = 130;
    private static final int NFC_SUCCESS = 131;
    private static final int IS_BACKGROUND = 132;
    private static final int RECORD_VIDEO_FOR_URL_SUCCESS = 133;
    private static final int WIFI_STATUS = 134;
    private static final int IS_SHOW_HOME_BACK = 135;
    private static final int TAKEPHOTO_EDITVIDEO_SUCCESS = 136;
    private static final int UPDATE_TASK_LIST = 137;
    private static final int GET_SHISHI_LOCATION_SUCCESS = 138;
    private static final int SHOW_NATIVE_INSPECTION_DETAIL = 139;

    private static final int DOWN_LOAD_INSPECTION = 140;

    public static final int NOTIFY_INSPECION_STATUS = 141;

    public static final int EVENT_BUS_INSPECTION_DOWNLOAD_SUCCESS = 142;

    //public static final int EVENT_BUS_UPKEEP = 143; //跳转至保养

    //public static final int EVENT_BUS_WORK_ORDER = 144; //跳转至工单

    public static final int EVENT_BUS_NOTIFY_H5_BACK = 145;  //原生页面点击返回按钮  通知H5

    public static final int EVENT_BUS_START_WORK_ACTIVITY_IS_WORK_ORDER = 146; //通知startWorkActivity isWorkOrder 为true

    public static final int CHANGE_INSPECTION_STATE = 150;

    public static H5Activity instance;
    private boolean mReceiverConnectTag = false;   //广播接受者标识
    private boolean mReceiverWIfiConnectTag = false;   //广播接受者标识
    private String takePicCallback, scanCallback, getAccessTokenCallback, currentLanguageCallback,
            saveH5DataToLocalCallBack, getH5DataForLocalCallback, takePhotoOkCallback, gpsCallback,
            gpsSlhishiCallback, nfcCallback, recordVideoCallback, wifiCallback, isShowHomeBackCallback;

    private String networkMode = "0";
    /**
     * 拍照上传的方式，1为base64，2为图片上传到客户端然后将返回的参数传递给H5
     */
    private String takePhotoType = "1";
    /**
     * 图片名称
     */
    private String imageName = "";

    /**
     * 视频id
     */
    private String videoId = "";

    /**
     * 要加载的URL
     */
    private String h5Url;
    private String title = "";

    /**
     * 工单类型和工单号
     */
    private String ownerObject, ownerId, ownerType;
    private SQLiteDatabase db;
    //离线是否上传图片
    private String offlineIsUploadImage = "true";

    private int canSelectNum = 9;  //选择图片或者视频剩余的可选数目
    /**
     * 进入界面时是否有网络
     */
    private boolean isConnect = true;

    /**
     * 判断是wifi还是移动网络
     *
     * @return
     */
    private String connectType = "MOBILE";
    /**
     * 信号差恢复到信号好的时候通知一次H5
     *
     * @return
     */
    private boolean signalRecovery;
    /**
     * wifi信号变强的标识,只发送一次
     *
     * @return
     */
    private boolean mobileSignalStrongFlag = false;
    /**
     * wifi信号变差的标识，只发送一次
     *
     * @return
     */
    private boolean mobileSignalWeakFlag = true;
    /**
     * wifi信号变强的标识,只发送一次
     *
     * @return
     */
    private boolean wifiSignalStrongFlag = false;
    /**
     * wifi信号变差的标识，只发送一次
     *
     * @return
     */
    private boolean wifiSignalWeakFlag = true;
    /**
     * wifi的信号值
     */
    private int wifilevel;
    /**
     * 移动网络信号值
     */
    private int gprsDbm;
    /**
     * H5界面是否加载成功
     */
    private String initHtmleCallbackResult = "false";
    private PowerManager.WakeLock wakeLock;
    private TelephonyManager telephonyManager;
    private PhoneStateListener myPhoneListener;
    private int asu;
    private int signalLevel = 4;
    private int wifiStrength;
    private String isH5Home;
    int i = 0;
    private Intent uploadImageIntent, gpsIntent, foregroundIntent;
    //是否开启了GPS的服务。这里为了防止宝安区项目修改包之后引起闪退
    private boolean isGPSOpen;
    private ChangePasswordDialog changePasswordDialog;

    //是否显示首页返回箭头
    private boolean isShowHomeBack;
    private LocationClient mLocationClient, mLocationClient_shishi;
    private List<PoiInfo> poiList;
    private int keyCode;
    private KeyEvent event;

    private Snackbar snackbar;

    List<MediaFile> mediaFiles = new ArrayList<>();

    private int curUploadPosion = -1;  //多图上传，当前正在上传的 第几张
    private String getStatusBarCallBack, getNoUploadFileNumCallback, startUploadFileCallback;

    private String inspectionListBackFunc;

    private DatabaseManager databaseManager;
    private String downLoadInspectionCallBack;

    public static boolean isOnline = true;


    @Override
    protected int getLayoutId() {
        return R.layout.activity_h5;
    }

    @SuppressLint("HandlerLeak")
    private Handler handler = new Handler() {
        @Override
        public void handleMessage(final Message msg) {
            super.handleMessage(msg);
            Log.e("handler", msg.what + "");
            switch (msg.what) {

                case 4001:
                    if (webView != null) {
                        webView.loadUrl("javascript:poorNetworkConditions");
                    }
                    break;

                case 4002:
                    if (webView != null) {
                        webView.loadUrl("javascript:waitingForNotification");
                    }
                    break;

                case 3005:
                    if (webView != null) {
                        List<Record> imagList = DBManager.getDBManager(context).getRecords(IMAGE.TABLE_NAME, null);
                        if (imagList == null || imagList.size() == 0) {
                            webView.loadUrl("javascript:uploadedAllImageSuccess");
                        }

                    }
                    break;
                case 3003:
                    if (webView != null) {
                        webView.loadUrl("javascript:uploadingOffLineFile");
                    }
                    break;
                case 3008:
                    if (webView != null) {
                        webView.loadUrl("javascript:poorNetworkConditions");
                    }
                    break;

                case 3000:
                    //Log.e("1111222", "startBatchUploadFile");
                    if (uploadImageIntent != null) {
                        stopService(uploadImageIntent);
                    }
                    uploadImageIntent = new Intent(getApplicationContext(), UploadImageService.class);
                    startService(uploadImageIntent);
                    break;
                case 3001://上传一个文件成功的回调
                    if (webView != null) {
                        //  List<ImageNameId> list=new ArrayList<>();
                        HandleJsEvent handle = (HandleJsEvent) msg.obj;
                        ImageNameId bean = new ImageNameId(handle.getOwnId(), handle.getImgName());
                        webView.loadUrl("javascript:startUploadFile('" + new Gson().toJson(bean) + "')");
                        Log.e("22222222", "javascript:startUploadFile('" + new Gson().toJson(bean) + "')");
                    }
                    break;
                case 3002://上传一个文件失败的回调
                    if (webView != null) {
                        HandleJsEvent handle = (HandleJsEvent) msg.obj;
                        webView.loadUrl("javascript:fileUploadFailed('" + handle.getOwnId() + "')");
                    }
                    //Log.e("1111", "333");
                    break;
                case 10005:
                    List<WorkOrderNumBean> list = UploadFileManager.getInstance().getWorkOrderList();
                    Map<String, String> hashMap = new HashMap<>();
                    if (list != null) {
                        for (int i = 0; i < list.size(); i++) {
                            hashMap.put(list.get(i).getWorkOrderId(), list.get(i).getNumber() + "");
                        }
                        String numCallback = new Gson().toJson(hashMap);
                        if (hashMap == null || hashMap.size() == 0) {
                            numCallback = "{}";
                        }
                        Log.e("22222222", "给h5的未上传的文件的工单号和数目----->" + numCallback + "-------" + "javascript:" + getNoUploadFileNumCallback + "('" + numCallback + "')");
                        if (webView != null) {
                            webView.loadUrl("javascript:" + getNoUploadFileNumCallback + "('" + numCallback + "')");
                        }
                    } else {
                        if (webView != null) {
                            webView.loadUrl("javascript:" + getNoUploadFileNumCallback + "('" + "{}" + "')");
                        }
                    }

                    break;
                case 10006:
                    UploadFileManager.getInstance().startQueryFile(H5Activity.this, true, true, new UploadFileManager.UploadSuccessBack() {
                        @Override
                        public void uploadFileSuccess(String gongdanId) {
                            Log.e("shuchang", "给h5的上传成功的工单号----->" + gongdanId);
                            if (webView != null) {
                                webView.loadUrl("javascript:" + getStatusBarCallBack + "('" + gongdanId + "')");
                            }
                        }
                    });
                    break;
                case SHOW_DIALOG:
                    loadingDialog.setText(getResources().getString(R.string.uploading));
                    showLoading();
                    break;
                case 10004:
                    MediaFile mediaFile = (MediaFile) ((Bundle) msg.obj).getSerializable("mediaFile");
                    takePhotoEditVideoOkCallBack(mediaFile.getVideoId());
                    uploadVideo(mediaFile.getPath(), mediaFile.getVideoId());
                    break;
                case 10003:
                    String namehh = ((Bundle) msg.obj).getString("namehh");
                    takePhotoEditImageOkCallBackWanzheng(namehh);
                    handleTakePicWanzheng(namehh);
                    break;
                case 10002:
                    mediaFiles = (List<MediaFile>) ((Bundle) msg.obj).getSerializable("mediaFiles");
                    if (mediaFiles.size() > 0) {
                        hasUploadCount = 0;
                        uploadCount = mediaFiles.size();
                        handler.sendEmptyMessage(SHOW_DIALOG);

                        String imageSizeStr = PreferenceManager.getDefaultSharedPreferences(context).getString(Constant.IMAGE_SIZE, "80");
                        try {
                            if (Integer.parseInt(imageSizeStr) > 100) {
                                imageSizeStr = "80";
                            }
                        } catch (Exception e) {
                            imageSizeStr = "80";
                        }
                        Log.e("shuchang", "开始处理图片--后端给的压缩比例----->" + imageSizeStr);
                        final String finalImageSizeStr = imageSizeStr;
                        for (int i = 0; i < mediaFiles.size(); i++) {
                            final int finalI = i;
                            new Thread(new Runnable() {
                                @Override
                                public void run() {
                                    if (ConfigManager.QUERY_URI == 0) {
                                        Log.e("shuchang", "图片压缩开始1--->" + System.currentTimeMillis());

                                        BitmapUtils.saveJPGE_After(H5Activity.this, BitmapFactory.decodeFile(mediaFiles.get(finalI).getPath()),
                                                mediaFiles.get(finalI).getImageName(), Integer.parseInt(finalImageSizeStr));

                                        Log.e("shuchang", "图片压缩结束1--->" + System.currentTimeMillis());
                                        String name;

                                        if (TextUtils.isEmpty(mediaFiles.get(finalI).getEditPath())) {
                                            name = mediaFiles.get(finalI).getImageName();
                                        } else {
                                            name = mediaFiles.get(finalI).getImageName().replace(".jpg", ".jpeg");
                                        }

                                        Message message = handler.obtainMessage(10003);
                                        Bundle bundle = new Bundle();
                                        bundle.putString("namehh", name);
                                        message.obj = bundle;
                                        handler.sendMessage(message);
                                    } else {
                                        Message message = handler.obtainMessage(10004);
                                        Bundle bundle = new Bundle();
                                        bundle.putSerializable("mediaFile", mediaFiles.get(finalI));
                                        message.obj = bundle;
                                        handler.sendMessage(message);
                                    }
                                }
                            }).start();

                        }

                    }
                    break;
                case 10001://color
                    Bundle colorBundle = (Bundle) msg.obj;
                    int color = colorBundle.getInt("color");
                    if (color == 0) { //白色
//                        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
//                            // 设置状态栏文字颜色为白色
//                            getWindow().getDecorView().setSystemUiVisibility(View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN | View.SYSTEM_UI_FLAG_LAYOUT_STABLE);
//                        }
                        initImmersionBar();
                    } else {  //深色
                        initImmersionBarTrue();
//                        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
//                            // 设置状态栏文字颜色为深色
//                            getWindow().getDecorView().setSystemUiVisibility(View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN | View.SYSTEM_UI_FLAG_LIGHT_STATUS_BAR);
//                            getWindow().setStatusBarColor(Color.TRANSPARENT);
//                        }
                    }
                    break;
                case 10000:
                    int heighth = ScreenUtils.getStatusBarHeight();
                    Log.e("shuchang", "状态栏的高--->" + heighth);
                    Log.e("shuchang", "给h5的方法名--->" + getStatusBarCallBack);
                    if (webView != null) {
                        webView.loadUrl("javascript:" + getStatusBarCallBack + "('" + Math.round(ScreenUtils.convertPxToCssPx(H5Activity.this, (float) heighth)) + "')");
                    }
                    break;
                case MSG_INIT_UI://初始化H5界面
//                    showLoading();
                    //初始化webview
                    initWebViewSetting();
                    /**网络监听广播，先初始化webview,否则调用网络通知NETWORK_OFFLINE崩溃*/
                    registerReceiver(mConnectivityChanged, new IntentFilter(ConnectivityManager.CONNECTIVITY_ACTION));
                    IntentFilter filter = new IntentFilter();
                    filter.addAction(WifiManager.RSSI_CHANGED_ACTION);
                    mReceiverConnectTag = true;
                    filter.addAction(WifiManager.WIFI_STATE_CHANGED_ACTION);
                    filter.addAction(WifiManager.NETWORK_STATE_CHANGED_ACTION);
                    context.registerReceiver(wifiConnectivityChanged, filter);
                    mReceiverWIfiConnectTag = true;
                    getPhoneState(context);
                    break;
                case INIT_CALLBACK_HTMLT_RESULT://H5界面是否加载完

                    if (initHtmleCallbackResult.equals("false")) {
                        final GPSCustomDialog dialog = new GPSCustomDialog(H5Activity.this, "当前无网络或网络异常,系统未加载成功,请在有网络时重试");
                        dialog.show();
                        dialog.setConfirmText("重新加载");
                        dialog.setClicklistener(new GPSCustomDialog.ClickListenerInterface() {
                            @Override
                            public void doConfirm() {
                                reloadWebview();
                                dialog.dismiss();
                            }

                            @Override
                            public void doCancel() {
                                dialog.dismiss();
                            }
                        });
                    }
                    break;
                case SET_CURRENT_LANGUAGE://设置当前语言种类

                    String langCode = sharedPrefs.getString("lang_code", "zh-CN");
                    XLog.i("langCode---" + langCode);
                    webView.loadUrl("javascript:" + currentLanguageCallback + "('" + langCode + "')");
                    break;
                case TAKEPIC_SUCCESS://BASE拍照成功
                    Bundle bundle = (Bundle) msg.obj;
                    Gson gson = new Gson();
                    String s = gson.toJson(presenter.getBase64SuccessList(bundle, takePhotoType, ownerId, ownerObject, ownerType,
                            TextUtils.isEmpty(bundle.getString(Constant.UPLOAD_IAMGE_NAME)) ? imageName : bundle.getString(Constant.UPLOAD_IAMGE_NAME)));
                    XLog.i("TAKEPIC_SUCCESS---" + s);
                    //上传成功
                    webView.loadUrl("javascript:" + takePicCallback + "('" + s + "')");
                    break;
                case WIFI_STATUS://获取网络状态

                    String status = (String) msg.obj;
                    webView.loadUrl("javascript:" + wifiCallback + "('" + status + "')");
                    break;
                case TAKEPHOTO_EDITIMAGE_SUCCESS://BASE拍照成功 在上传服务器之前通知h5
                    Bundle takeOkBundle = (Bundle) msg.obj;
                    Gson takeOkgson = new Gson();
//                    String localpath = takeOkBundle.getString(Constant.UPLOAD_IAMGE_LOCAL_PATH);
                    String ss = takeOkgson.toJson(presenter.getBase64SuccessList(takeOkBundle,
                            takePhotoType, ownerId, ownerObject, ownerType,
                            TextUtils.isEmpty(takeOkBundle.getString(Constant.UPLOAD_IAMGE_NAME)) ? imageName : takeOkBundle.getString(Constant.UPLOAD_IAMGE_NAME)));
                    //Log.e("shuchang11111", "给h5的图片相关信息------>" + ss);
                    //上传成功
                    webView.loadUrl("javascript:" + takePhotoOkCallback + "('" + ss + "')");
                    break;

                case TAKEPHOTO_EDITVIDEO_SUCCESS://BASE拍照成功
                    Bundle takeOkVideoBundle = (Bundle) msg.obj;
                    Gson takeOkVideogson = new Gson();
                    String sss = takeOkVideogson.toJson(presenter.getVideoSuccessList(takeOkVideoBundle, takePhotoType, ownerId, ownerObject,
                            ownerType, takeOkVideoBundle.getString("videoId", videoId)));
                    //上传成功
                    Log.e("shuchang", "上传前给到h5--->" + sss);
                    webView.loadUrl("javascript:" + takePhotoOkCallback + "('" + sss + "')");
                    break;

                case TAKEPIC_UPLOAD://图片上传到客户端
                    final Bundle bundle1 = msg.getData();
//                    loadingDialog.setText(getResources().getString(R.string.uploading));
//                    showLoading();
                    Log.e("shuchang", "开始上传--->" + System.currentTimeMillis());
                    if (loadingDialog != null) {
                        loadingDialog.show();
                    }
                    presenter.uploadImgForClient(bundle1.getString("imagePath"), bundle1.getString(Constant.UPLOAD_IAMGE_NAME));

                    break;

                case SCAN_SUCCESS://扫码成功
                    String assetno = (String) msg.obj;
                    XLog.i("NFC通过扫码返回的内容:" + assetno);
                    webView.loadUrl("javascript:" + scanCallback + "('" + assetno + "')");
                    break;
                case NFC_SUCCESS://NFC内容

                    String nfcStr = (String) msg.obj;
                    XLog.i("NFC直接返回的内容:" + nfcStr);
                    webView.loadUrl("javascript:" + nfcCallback + "('" + nfcStr + "')");
                    break;
                case TAKEPIC_FOR_URL_SUCCESS://图片上传到客户端成功
                    Bundle bundle2 = (Bundle) msg.obj;
                    String json = bundle2.getString("json");

                    webView.loadUrl("javascript:" + takePicCallback + "('" + json + "')");
                    break;
                case GET_ACCESSTOKEN_SUCCESS://获取token成功
                    String accessToken = (String) msg.obj;
                    Log.e("shuchang", "toh5的token--->" + accessToken);
                    webView.loadUrl("javascript:" + getAccessTokenCallback + "('" + accessToken + "')");
                    break;
                case ONKEYDOWN_SUCCESS://处理回退键
                    KLog.e(Constant.isBao);
                    if (Constant.isBao) {
                        finish();
                    } else {
                        if (webView != null) {
                            webView.loadUrl("javascript:" + "onNativeGoBack()");
                        }
                    }
                    break;
                case NETWORK_ONLINE://从断网到有网通知H5
                    //再次启动Service
                    try {
                        if (uploadImageIntent != null) {
                            stopService(uploadImageIntent);
                        }
                        Intent intentFive = new Intent(H5Activity.this, UploadImageService.class);
                        startService(intentFive);
                    } catch (Exception e) {
                    }
                    i++;
                    setWebcarch();
                    XLog.i("从断网到有网通知H5" + i + "---时间戳---->" + System.currentTimeMillis());
                    webView.loadUrl("javascript:" + "onNetworkOnline(" + System.currentTimeMillis() + ")");
                    break;
                case NETWORK_OFFLINE://从有网到断网通知H5
                    XLog.i("从有网到断网通知H5" + "---时间戳---->" + System.currentTimeMillis());
                    setWebcarch();
                    webView.loadUrl("javascript:" + "onNetworkOffline(" + System.currentTimeMillis() + ")");
                    break;
                case ONE_CLICK://单击事件
                    handler.sendEmptyMessage(ONKEYDOWN_SUCCESS);
                    break;
                case DOUBLE_CLICK://双击事件
                    exit();
                    break;
                case RELOAD_URL://重新加载URL
                    webView.clearView();
                    Log.e("h5Url11", h5Url);
                    webView.loadUrl(h5Url);
                    break;
                case CLEAR_STORAGE://清理localStorage缓存
                    webView.loadUrl("javascript:" + "clearCacheForApp()");
                    sharedPrefs.edit().putBoolean(Constant.CLEAR_LOCAL_STORAGE, false).apply();
                    XLog.i("回调了:clearCacheForApp");
                    break;
                case SAVE_H5DATA_TO_LOCAL://保存H5数据到本地
                    String saveResult = (String) msg.obj;
                    webView.loadUrl("javascript:" + saveH5DataToLocalCallBack + "('" + saveResult + "')");
                    break;
                case GET_H5DATA_FOR_LOCAL://获取本地H5数据ImageUtils
                    Bundle bundles = (Bundle) msg.obj;
                    String result = bundles.getString("json");
                    String uuid = bundles.getString("uuid");
                    XLog.i("回调了:" + getH5DataForLocalCallback + uuid + "--" + result);
                    webView.loadUrl("javascript:" + getH5DataForLocalCallback + "('" + uuid + "','" + result + "')");
                    break;
                case GET_LOCATION_SUCCESS://获取经纬度成功
                    String de = "{\"sLon\":\"000.00\", \"sLon\":\"00.00\", \"Position\":\"暂未定位成功\"}";
                    String gpsStr = sharedPrefs.getString(Constant.LON_LAT_DESC, de);
                    Log.e("shuchang", "getLongAndLat--->" + gpsStr);
                    if (webView != null) {
                        webView.loadUrl("javascript:" + gpsCallback + "('" + gpsStr + "')");
                    }
                    break;

                case GET_SHISHI_LOCATION_SUCCESS://获取时时经纬度成功 "4.9E-324"
                    Log.e("shuchang", "getshishiLongAndLat--->" + msg.obj);
                    mLocationClient_shishi.stop();
                    if (webView != null) {
                        webView.loadUrl("javascript:" + gpsSlhishiCallback + "('" + msg.obj + "')");
                    }
                    break;
                case IS_BACKGROUND://通知APP在前后台
                    int backgroundType = (int) msg.obj;
                    String backgroundTCallBack = "appScreenStatus";
                    if (webView != null) {
                        webView.loadUrl("javascript:" + backgroundTCallBack + "('" + backgroundType + "')");
                    }
                    if (uploadImageIntent != null) {
                        stopService(uploadImageIntent);
                    }
                    uploadImageIntent = new Intent(getApplicationContext(), UploadImageService.class);
                    startService(uploadImageIntent);
                    break;
                case RECORD_VIDEO_FOR_URL_SUCCESS://视频上传到客户端成功
                    Bundle bundleVideo = (Bundle) msg.obj;
                    String jsonVideo = bundleVideo.getString("json");
                    Log.e("shuchang", "上传视频结果给h5--->" + jsonVideo);
                    webView.loadUrl("javascript:" + recordVideoCallback + "('" + jsonVideo + "')");
                    XLog.i(jsonVideo);
                    break;
                case IS_SHOW_HOME_BACK://视频上传到客户端成功

                    webView.loadUrl("javascript:" + isShowHomeBackCallback + "('" + isShowHomeBack + "')");
                    break;
                case UPDATE_TASK_LIST://收到消息通知h5
                    String message = (String) msg.obj;
                    XLog.i("刷新任务列表:" + message);
                    webView.loadUrl("javascript:" + "updateTaskList" + "('" + message + "')");
                    break;
                case SHOW_NATIVE_INSPECTION_DETAIL:
                    String data = (String) msg.obj;
                    Log.d("hhhhhhh", data);

                    try {
                        JSONObject jsonObject = new JSONObject(data);
                        String id = jsonObject.getString("id"); //巡检单ID
                        String taskId = jsonObject.getString("taskId"); //待办ID
                        presenter.getSharedPrefs().edit().putString("id", id).apply();
                        presenter.getSharedPrefs().edit().putString("taskId", taskId).apply();
                        if (jsonObject.has("backFunc")) {
                            inspectionListBackFunc = jsonObject.getString("backFunc");
                        }
                        sharedPrefs.edit().putInt("curPage", -1).apply();
                        sharedPrefs.edit().putString("curWorkid", "").apply();
                        CheckDetailsActivity.startActivity(context, data);
                    } catch (JSONException e) {
                        Log.e("巡检列表点击事件", "catch" + data);
                    }
                    break;

                case DOWN_LOAD_INSPECTION:
                    String params = (String) msg.obj;
                    try {
                        KLog.e(params);
                        JSONObject jsonObject = new JSONObject(params);
                        String id = jsonObject.getString("id"); //巡检单ID
                        String taskId = jsonObject.getString("taskId"); //待办ID
                        //detailSuccessCallBack = jsonObject.getString("name"); //成功返回的回调
                        downLoadInspectionCallBack = jsonObject.getString("backFunc");  //回调
                        if (!NetworkUtils.isAvailable(context)) {
                            return;
                        }
                        presenter.getDetails(id);
                        KLog.e("DOWN_LOAD_INSPECTION");
//                      webView.loadUrl("javascript:" + detailSuccessCallBack + "('" + s + "')");
                    } catch (JSONException e) {
                        Log.e("巡检下载按钮===========》", params);
                    }

                    break;

                case NOTIFY_INSPECION_STATUS:
                    showLoading();
                    HandleJsEvent handle = (HandleJsEvent) msg.obj;
                    String paramsValue = handle.getOwnId();
                    String[] paramsList = paramsValue.split(",");
                    if (paramsList.length == 3) {
                        String id = paramsList[0];
                        String taskId = paramsList[1];
                        String state = paramsList[2];
                        Map<String, Object> map = new HashMap<>();
                        map.put("id", id);
                        map.put("taskId", taskId);
                        map.put("status", state);
                        String jsonData = new Gson().toJson(map);

                        Log.e("通知JS刷新巡检任务状态====", "javascript:" + "inspectionDetialStateChange" + "('" + jsonData + "')");
                        webView.loadUrl("javascript:" + "inspectionDetialStateChange" + "('" + jsonData + "')");
                        //webView.loadUrl("javascript:" + "inspectionDetialStateChange" + "({" + "id:" + id + "," + "taskId:" + taskId + "," + "status:" + state + "})");
                        webView.postDelayed(new Runnable() {
                            @Override
                            public void run() {
                                hideLoading();
                            }
                        }, 1500);
                    }

                    break;

                case EVENT_BUS_INSPECTION_DOWNLOAD_SUCCESS:
                    webView.loadUrl("javascript:" + inspectionListBackFunc + "()");
                    break;
//                case EVENT_BUS_UPKEEP:
//                    //http://192.168.200.67/h5/mytask/?accessToken=b7b9e73c-0d2d-41f0-b54e-19dd68e5912d#/pmtask/read/1058338075740086303/1058338075740086290
//                    String baseUrl = PreferenceManager.getDefaultSharedPreferences(context).getString(Constant.BASE_ADDRESS_URL, "");
//                    String value = ((HandleJsEvent) msg.obj).getOwnId();
//                    String[] splitValue = value.split(",");
//                    String id = splitValue[0];
//                    String taskId = splitValue[1];
//                    String url = baseUrl + "/h5/mytask/?accessToken=" + UserHelper.getToken() + "#/pmtask/read/" + id + "/" + taskId;
//                    webView.loadUrl(url);
//                    break;
//                case EVENT_BUS_WORK_ORDER:
//                    String baseUrl1 = PreferenceManager.getDefaultSharedPreferences(context).getString(Constant.BASE_ADDRESS_URL, "");
//                    String value1 = ((HandleJsEvent) msg.obj).getOwnId();
//                    String[] splitValue1 = value1.split(",");
//                    String id1 = splitValue1[0];
//                    String taskId1 = splitValue1[1];
//                    String url1 = baseUrl1 + "/h5/mytask/?accessToken=" + UserHelper.getToken() + "#/srtask/detail/" + id1 + "/" + taskId1 + "?from=app";
//                    webView.loadUrl(url1);
//                    break;
                case EVENT_BUS_NOTIFY_H5_BACK:
                    webView.loadUrl("javascript:" + "onAppWebviewShow()");
                    KLog.e("1111111");
                    break;
                case EVENT_BUS_START_WORK_ACTIVITY_IS_WORK_ORDER:
                    finish();
                    EventBus.getDefault().post(new HandleJsEvent(2000, ""));
                    break;
                case CHANGE_INSPECTION_STATE:
                    String stateJson = (String) msg.obj;
                    FMCApplication.changeInspectionStateJson = stateJson;
                    break;
                case 998:
                    UploadHandlerBean uploadHandlerBean = (UploadHandlerBean) msg.obj;
                    webView.loadUrl("javascript:" + uploadHandlerBean.getAction() + "('" + uploadHandlerBean.getBase64() + "')");
                    break;
                case 987:
                    Map<String, UploadImageBean> map = CacheHelper.getInstance().getUpImageList();
                    webView.loadUrl("javascript:" + "updateInspOffineUploadTask" + "('" + GsonUtil.BeanToJson(map) + "')");
                    break;
                case 988:
                    Map<String, UploadImageBean> map1 = CacheHelper.getInstance().getUpImageList();
                    KLog.e("22222", GsonUtil.BeanToJson(map1));
                    webView.loadUrl("javascript:" + "updateInspOffineUploadTask" + "('" + GsonUtil.BeanToJson(map1) + "')");
                    break;
                default:
                    break;
            }
        }
    };


    public Map<String, List<CaUploadImage>> groupByPoint(List<CaUploadImage> personList) {
        Map<String, List<CaUploadImage>> groupedMap = new HashMap<>();
        for (CaUploadImage person : personList) {
            String age = person.getListId();
            if (!groupedMap.containsKey(age)) {
                groupedMap.put(age, new ArrayList<>()); // 初始化分组
            }
            groupedMap.get(age).add(person); // 添加到对应分组
        }
        return groupedMap;
    }

    //获取开始暂停数
    public Map<String, List<GETREPORTBean>> groupByPointStartPause() {
        List<GETREPORTBean> list = CacheHelper.getInstance().getOnLineNoGET_REPORT_STATUS();
        Map<String, List<GETREPORTBean>> groupedMap = new HashMap<>();
        for (GETREPORTBean person : list) {
            String age = person.getListId();
            if (!groupedMap.containsKey(age)) {
                groupedMap.put(age, new ArrayList<>()); // 初始化分组
            }
            groupedMap.get(age).add(person); // 添加到对应分组
        }
        return groupedMap;
    }


    public Map<String, List<SubMitPointBean>> groupSubmitByPoint(List<SubMitPointBean> personList) {
        Map<String, List<SubMitPointBean>> groupedMap = new HashMap<>();
        for (SubMitPointBean person : personList) {
            String age = person.getListId();
            if (!groupedMap.containsKey(age)) {
                groupedMap.put(age, new ArrayList<>()); // 初始化分组
            }
            groupedMap.get(age).add(person); // 添加到对应分组
        }
        return groupedMap;
    }

    public int getStartPause(String listId) {
        List<GETREPORTBean> list = CacheHelper.getInstance().getOnLineNoGET_REPORT_STATUS();
        int isHave = 0;
        for (int i = 0; i < list.size(); i++) {
            if (TextUtils.equals(listId, list.get(i).getListId())) {
                isHave = isHave + 1;
            }
        }
        return isHave;

    }


    @Override
    protected void onNewIntent(Intent intent) {
        super.onNewIntent(intent);
        //setIntent(intent);
//        String url=intent.getStringExtra(Constant.H5_URL);
//        if (webView != null&&!TextUtils.isEmpty(url)) {
//            webView.loadUrl(url);
//        }
//            if (sharedPrefs.getBoolean(Constant.OPEN_START_MODE, false)) {
//                webView.loadUrl(url + "&isdebug=true");
//            } else {
//                webView.loadUrl(url);
//            }
//        }
        KLog.e("onNewIntent", this);
        //init(null);
    }

    private LinearLayout ll_loading;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        KLog.e("onCreate");
        super.onCreate(savedInstanceState);
        view_back = findViewById(R.id.view_back);
        ll_loading = findViewById(R.id.ll_loading);
        String loginUserid = UserHelper.getUserId();
        SharedPrefUtils.getInstance(context).putString("key_user_id", loginUserid);
        receiveNfcResult();
        Constant.isSll = true;
        getGps();
        presenter.getResult();
        // if(NetworkUtils.isAvailable(context)){
        presenter.getOperateReportList();
        // }
        //启动服务 检测网络
        Intent serviceIntent = new Intent(this, NetworkListenerService.class);
        startService(serviceIntent);
        view_back.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                simulateKeyDown();
                view_back.setVisibility(View.GONE);
            }
        });

    }

    public void simulateKeyDown() {
        int keyCode = KeyEvent.KEYCODE_BACK; // 模拟按下返回键
        long downTime = System.currentTimeMillis(); // 按下时间
        long eventTime = System.currentTimeMillis(); // 事件时间

        // 创建 KeyEvent 对象
        KeyEvent event = new KeyEvent(downTime, eventTime, KeyEvent.ACTION_DOWN, keyCode, 0);

        // 手动调用 onKeyDown
        onKeyDown(keyCode, event);
    }

    @Override
    protected void onRestart() {
        super.onRestart();
    }


    @Override
    protected void init(Bundle savedInstanceState) {
        databaseManager = new DatabaseManager(context);
//
//        if (Build.VERSION.SDK_INT >= 21) {
//            View decorView = getWindow().getDecorView();
//            decorView.setSystemUiVisibility(View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN | View.SYSTEM_UI_FLAG_LAYOUT_STABLE);
//            getWindow().setStatusBarColor(Color.TRANSPARENT);
//        }


        instance = this;
        findview();
        if (standard) {
            //第一次登录APP需要提示设置消息的提示框
            String firstNotice = sharedPrefs.getString(Constant.FIRST_NOTICE, "");
            if (TextUtils.isEmpty(firstNotice)) {
                NoticeTipsDialog noticeTipsDialog = new NoticeTipsDialog(context);
                noticeTipsDialog.show();
            }
            isShowHomeBack = false;


            boolean isLinkOssLogin = sharedPrefs.getBoolean(Constant.IS_LINK_OSS_LOGIN, false);
            String isOkGetSysInfo = PreferencesHelper.getData("isOkGetSysInfo");
            //领展oss登录不需要
            if (!isLinkOssLogin) {
                /**是否强制修改初始密码*/
                if (!TextUtils.isEmpty(UserHelper.getUserId()))
                    if (!"true".equals(isOkGetSysInfo)) {
                        presenter.getpwdEnforced(UserHelper.getToken(), UserHelper.getUserId());
                    }
            }
            //设置标题名称
            SystemSetting systemSetting = PreferencesHelper.getData(SystemSetting.class);
            if (systemSetting != null) {
                SystemSetting.RecordBean record = systemSetting.getRecord();
                if (record != null) {
                    String is_gps = record.getIS_GPS();
                    if (!TextUtils.isEmpty(is_gps)) {
                        //开启员工GPS追踪
                        if (is_gps.equals("1")) {
                            if (!TextUtils.isEmpty(record.getTRAJECTORY_CYCLE())) {
                                if (Integer.parseInt(record.getTRAJECTORY_CYCLE()) > 0) {
                                    gpsIntent = new Intent(getApplicationContext(), LocationService.class);
                                    gpsIntent.putExtra("gpsTime", record.getTRAJECTORY_CYCLE());
                                    startService(gpsIntent);
                                    isGPSOpen = true;
                                }
                            }
                        }
                    }
                }
            }
            /**启动上传图片的服务，如果有图片则上传*/
            if (uploadImageIntent != null) {
                stopService(uploadImageIntent);
            }
            uploadImageIntent = new Intent(getApplicationContext(), UploadImageService.class);
            startService(uploadImageIntent);
            //启动一个前端服务
//            foregroundIntent = new Intent(getApplicationContext(), ForegroundService.class);
//            startService(foregroundIntent);
            //设置设备id给后台
            presenter.updateDeviceId();

            //获取极光推送别名配置
            presenter.getJpushalias();

            /**检查版本*/
            if (!Constant.isBao) {
                presenter.checkAppVersion(this);
            }
            /**记录登录足迹*/
//            String dailyLoginTime = sharedPrefs.getString(Constant.LOGIN_TIME, "");
//            XLog.i("当前时间1："+dailyLoginTime);
//            if (TextUtils.isEmpty(dailyLoginTime)){
//                presenter.dailyLoginTime();
//            }else {
//                if (!dailyLoginTime.equals(DateUtil.getCurrentDate())){
//                    presenter.dailyLoginTime();
//                }
//            }
            PowerManager pm = (PowerManager) getSystemService(Context.POWER_SERVICE);
            wakeLock = pm.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, LocationService.class.getName());
            wakeLock.acquire();
        } else {
            isShowHomeBack = true;
        }
        if (savedInstanceState != null) {
            this.imageName = savedInstanceState.getString("imageName");
        }

        //是否显示标题栏
        boolean hideH5Header = getIntent().getBooleanExtra(Constant.HIDE_HEADER, false);
        //标题
        title = getIntent().getStringExtra(Constant.H5_TITLE);
        //连接地址
        h5Url = getIntent().getStringExtra(Constant.H5_URL);

//        h5Url="file:///android_asset/test.html";
        if (TextUtils.isEmpty(h5Url)) {
            String extras = "";
            if (getIntent().getData() != null) {
                extras = getIntent().getData().toString();
            }
            if (TextUtils.isEmpty(extras) && getIntent().getExtras() != null) {
                extras = getIntent().getExtras().getString("JMessageExtra");
            }
            if (TextUtils.isEmpty(extras)) return;
            JSONObject json = null;
            XLog.i("H5:" + extras);
            try {
                json = new JSONObject(extras);
                JSONObject object = json.optJSONObject("n_extras");

                String url = object.optString("url");
                if (!TextUtils.isEmpty(url)) {
                    if (url.startsWith("http")) {
                        if (url.contains("#accessToken#")) {
                            h5Url = url.replace("#accessToken#", UserHelper.getToken());
                        } else if (url.contains("{accessToken}")) {
                            h5Url = url.replace("{accessToken}", UserHelper.getToken());
                        }
                    } else {
                        if (url.contains("#accessToken#")) {
                            h5Url = sharedPrefs.getString(Constant.BASE_ADDRESS_URL, "") + url.replace("#accessToken#", UserHelper.getToken());
                        } else if (url.contains("{accessToken}")) {
                            h5Url = url.replace("{accessToken}", UserHelper.getToken());
                        }
                    }
                }
            } catch (JSONException e) {
                e.printStackTrace();
            }

        }
        XLog.i("H5:" + h5Url);

        //是否显示原生的标题栏，一般不显示
        if (hideH5Header) {
            titlebar.setVisibility(View.VISIBLE);
            titlebar.setTitle(title);
        } else {
            titlebar.setVisibility(View.GONE);
        }
        getWindow().setFormat(PixelFormat.TRANSLUCENT);
        //开启硬件加速
        try {
            if (Integer.parseInt(Build.VERSION.SDK) >= 11) {
                getWindow().setFlags(WindowManager.LayoutParams.FLAG_HARDWARE_ACCELERATED, WindowManager.LayoutParams.FLAG_HARDWARE_ACCELERATED);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        /**加载dialog*/
        handler.sendEmptyMessageDelayed(MSG_INIT_UI, 10);

    }

    /**
     * 弹出修改密码界面
     */
    private void modifiyPassword() {
        //修改密码的dialog
        changePasswordDialog = new ChangePasswordDialog(this);
        changePasswordDialog.show();
        changePasswordDialog.forcePasswordChange(true);
        changePasswordDialog.setClicklistener(new ChangePasswordDialog.ClickListenerInterface() {
            @Override
            public void doConfirm(String initialPassword, String newPassword, String againPassword) {

                String appName = (String) Utility.getMetaData(context, Constant.APP_NAME);
                if (Constant.APP_NAME_ZSJ.equals(appName)) {
                    //修改密码接口
                    presenter.getSM2Key(initialPassword, newPassword, againPassword);
                } else {
                    //修改密码接口
                    presenter.modifyPassword(initialPassword, newPassword, againPassword);
                }


            }

            @Override
            public void doCancel() {
                Utility.startLoginActivityOrClearData(H5Activity.this);
            }
        });

    }

    @Override
    public void modifyPasswordSuccess() {
        sharedPrefs.edit().putString(Constant.PSD_MODIFIY, "0").apply();
        if (changePasswordDialog != null) changePasswordDialog.dismiss();
    }

    @Override
    public void getpwdEnforcedSuccess(String pwdEnforced) {
        if (TextUtils.isEmpty(pwdEnforced)) {
            return;
        }
        sharedPrefs.edit().putString(Constant.PSD_MODIFIY, pwdEnforced).apply();
        if (!pwdEnforced.equals("0") || !PasswordUtils.isModfiyPassword(this)) {
            modifiyPassword();

        }
    }

    @Override
    public void sysKehdescSuccess(SysKesDescBean baseData) {
        if (baseData != null) {
            UserHelper.saveSysKeyDescBean(baseData);
        }
    }

    @Override
    public void sysKehdescFail() {

    }

    @Override
    public void getDetailSuccess(GetDetailsBean baseData) {
        //存数据的时候 把ID 拼接上
        presenter.getDetailsHistory(baseData.getRecord().getId(), baseData.getRecord().getProjId());
        databaseManager.upsertJson("CheckDetailsActivity" + baseData.getRecord().getId(), GsonUtil.BeanToJson(baseData));

    }

    @Override
    public void getDetailFail() {
        webView.loadUrl("javascript:" + downLoadInspectionCallBack + "('" + 4 + "')");
    }

    public static String replacementInfo(String str, String keyword, String before) {
        StringBuilder sb = new StringBuilder(str);
        String rs = str;
        try {
            //字符第一次出现的位置
            int index = sb.indexOf(keyword);
            while (index != -1) {
                sb.insert(index, before);
                //下一次出现的位置，
                index = sb.indexOf(keyword, index + before.length() + 1);
            }
            rs = sb.toString();
        } catch (Exception e) {
            System.out.println("更换字符错误！！！");
            e.printStackTrace();
        }
        return rs;
    }

    private void reStartActivity() {
        Intent intent = getIntent();
        finish();
        startActivity(intent);
    }

    //初始化webview
    private void initWebViewSetting() {
        webView = new X5WebView(this, null);
        FrameLayout.LayoutParams params = new FrameLayout.LayoutParams(FrameLayout.LayoutParams.FILL_PARENT, FrameLayout.LayoutParams.FILL_PARENT);
        webFramlayout.addView(webView, params);
        webView.setWebViewClient(new H5WebViewClient(webView, this, context));
        webView.setWebChromeClient(new WebChromeClient());
        webView.addJavascriptInterface(new JsInterface(this, this), "android");
        webView.getSettings().setAllowFileAccess(true);


        //  webView.setLayerType(View.LAYER_TYPE_HARDWARE, null);


        // 设置 X5WebViewClient
        webView.setWebViewClient(new WebViewClient() {
            @Override
            public void onReceivedError(WebView view, int errorCode, String description, String failingUrl) {
                // 渲染进程崩溃或其他加载错误
                Log.e("X5WebView", "Error code: " + errorCode + ", Description: " + description + ", Failing URL: " + failingUrl);
                // 可以在这里重新加载页面或显示错误提示
//                WebSettings webSetting = view.getSettings();
//                webSetting.setJavaScriptEnabled(true);
                // view.reload();
                reStartActivity();
            }

            @Override
            public boolean onRenderProcessGone(WebView wb, RenderProcessGoneDetail renderProcessGoneDetail) {
                if (renderProcessGoneDetail.didCrash()) {
                    // 渲染进程崩溃
                    Log.e("X5WebView", "Render process crashed");
                    // 可以在这里重新加载页面或显示错误提示
                    // webView.loadUrl("about:blank"); // 清空内容
                    //wb.getUrl()
                    // initWebViewSetting(wb);
//                    WebSettings webSetting = wb.getSettings();
//                    webSetting.setJavaScriptEnabled(true);
                    // wb.reload();
                    reStartActivity();
                    return true; // 表示已经处理了崩溃
                }
                return super.onRenderProcessGone(webView, renderProcessGoneDetail);
            }

            @Override
            public boolean shouldOverrideUrlLoading(WebView view, WebResourceRequest request) {
                view.loadUrl(request.getUrl().toString());

                return true;
            }

            @Override
            public void onPageFinished(WebView view, String url) {
                super.onPageFinished(view, url);
                // 页面加载完成
                ll_loading.setVisibility(View.GONE);
                Log.d("X5WebView", "Page finished loading: " + url);
            }
        });

        if (!TextUtils.isEmpty(h5Url)) {
            if (h5Url.contains("/h5/mytask")) {
                h5Url = replacementInfo(h5Url, "/h5/mytask", Url.API);
            }

            XLog.i(h5Url);

            if (sharedPrefs.getBoolean(Constant.OPEN_START_MODE, false)) {
                webView.loadUrl(h5Url + "&isdebug=true");
            } else {
                webView.loadUrl(h5Url);
            }
            Constant.H5ActivityUrl = h5Url;

            Log.e("h5Url22", h5Url);
//        webView.loadUrl("file:///android_asset/test.html");
        }

        setNetworkMode("0");
    }

    @Override
    public void onReceivedError(WebView view, int errorCode, String description, String failingUrl) {
    }


    //页面加载完成后调用清理数据缓存的函数
    @Override
    public void onreceivedSuccess(String url) {
        boolean isClear = sharedPrefs.getBoolean(Constant.CLEAR_LOCAL_STORAGE, false);
        if (isClear) {
            handler.sendEmptyMessage(CLEAR_STORAGE);
        }

    }

    /**
     * 拍照
     * type：拍照后上传图片的方式，max：拍照的最大数量，ownerObject，ownerType，ownerId这三个参数H5做什么用的不清楚，takePicCallback拍照的回调函数
     *
     * @param takePicCallback
     */
    @Override
    public void takePhoto(String type, String max, String ownerObject, String ownerType, String ownerId, String takePicCallback) {
        Log.e("shuchang", "h5---takePhoto-------1->");
        this.takePhotoType = type;
        this.takePicCallback = takePicCallback;
        this.ownerObject = ownerObject;
        this.ownerId = ownerId;
        this.ownerType = ownerType;
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
            //动态申请权限
            applyPermissions();
        } else {
            nativeTakePhoto();
        }
    }

    @Override
    public void takePhoto(String type, String max, String ownerObject, String ownerType, String ownerId, String takePicCallback, String offlineIsUploadImage) {
        Log.e("shuchang", "h5---takePhoto-------2->");
        this.offlineIsUploadImage = offlineIsUploadImage;//离线是否上传图片
        this.takePhotoType = type;
        this.takePicCallback = takePicCallback;
        this.ownerObject = ownerObject;
        this.ownerId = ownerId;
        this.ownerType = ownerType;
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
            //动态申请权限
            applyPermissions();
        } else {
            nativeTakePhoto();
        }
    }

    @Override
    public void takePhoto(String type, String max, String ownerObject, String ownerType, String ownerId, String takePicCallback, String offlineIsUploadImage, String takePhotoOkCallback) {
        Log.e("shuchang", "h5---takePhoto-------3->");
        this.offlineIsUploadImage = offlineIsUploadImage;
        this.takePhotoType = type;
        this.takePicCallback = takePicCallback;
        this.ownerObject = ownerObject;
        this.ownerId = ownerId;
        this.ownerType = ownerType;
        this.takePhotoOkCallback = takePhotoOkCallback;//拍照后图片在上传之前是否需要回调通知H5
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
            //动态申请权限
            applyPermissions();
        } else {
            nativeTakePhoto();
        }

    }

    //是否打开相册
    @Override
    public void takePhoto(String type, String max, String ownerObject, String ownerType, String ownerId, String takePicCallback, String offlineIsUploadImage, String takePhotoOkCallback, String openAlbum) {
        Log.e("shuchang", "h5---takePhoto-------4->");
        this.offlineIsUploadImage = offlineIsUploadImage;
        this.takePhotoType = type;
        this.takePicCallback = takePicCallback;
        this.ownerObject = ownerObject;
        this.ownerId = ownerId;
        this.ownerType = ownerType;
        this.takePhotoOkCallback = takePhotoOkCallback;//拍照后图片在上传之前是否需要回调通知H5
        //0不打开相册,1打开相册
        if (openAlbum.equals("1")) {
            showAlbumDialog();
        } else {
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
                //动态申请权限
                applyPermissions();
            } else {
                nativeTakePhoto();
            }

        }
    }


    List<String> permissionLists1 = new ArrayList<>();
    List<String> permissionLists2 = new ArrayList<>();
    List<String> permissionLists3 = new ArrayList<>();
    List<String> permissionLists4 = new ArrayList<>();
    public static boolean isDuoxuan = false;

    //拍照和录像选择
    @Override
    public void takePhoto(String type, String max, String ownerObject, String ownerType, String ownerId, String takePicCallback, String offlineIsUploadImage,
                          String takePhotoOkCallback, String openAlbum,
                          String recordVideoCallback, String openRecordVideo, String openVideoAlbum
    ) {
        Log.e("shuchang", "h5---takePhoto-------5->");
        isDuoxuan = false;
        this.offlineIsUploadImage = offlineIsUploadImage;
        this.takePhotoType = type;
        this.takePicCallback = takePicCallback;
        this.ownerObject = ownerObject;
        this.ownerId = ownerId;
        this.ownerType = ownerType;
        this.takePhotoOkCallback = takePhotoOkCallback;//拍照后图片在上传之前是否需要回调通知H5
        this.recordVideoCallback = recordVideoCallback;//拍照后图片在上传之前是否需要回调通知H5
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
            //动态申请权限
            if (Build.VERSION.SDK_INT >= 23) {
                permissionLists1.clear();
                permissionLists2.clear();
                permissionLists3.clear();
                permissionLists4.clear();
                if (ContextCompat.checkSelfPermission(this, Manifest.permission.CAMERA) != PackageManager.PERMISSION_GRANTED) {
                    permissionLists1.add(Manifest.permission.CAMERA);
                }
                if (ContextCompat.checkSelfPermission(this, Manifest.permission.RECORD_AUDIO) != PackageManager.PERMISSION_GRANTED) {
                    permissionLists2.add(Manifest.permission.RECORD_AUDIO);
                }
                if (ContextCompat.checkSelfPermission(this, Manifest.permission.READ_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) {
                    permissionLists3.add(Manifest.permission.READ_EXTERNAL_STORAGE);
                }
                if (ContextCompat.checkSelfPermission(this, Manifest.permission.WRITE_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) {
                    permissionLists3.add(Manifest.permission.WRITE_EXTERNAL_STORAGE);
                }

                if (ContextCompat.checkSelfPermission(H5Activity.this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
                    permissionLists4.add(Manifest.permission.ACCESS_FINE_LOCATION);
                }
                if (ContextCompat.checkSelfPermission(H5Activity.this, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
                    permissionLists4.add(Manifest.permission.ACCESS_COARSE_LOCATION);
                }
//                if (ContextCompat.checkSelfPermission(H5Activity.this, Manifest.permission.FOREGROUND_SERVICE) != PackageManager.PERMISSION_GRANTED) {
//                    permissionLists4.add(Manifest.permission.FOREGROUND_SERVICE);
//                }

                if (permissionLists1.size() > 0) {//说明肯定有拒绝的权限
                    ActivityCompat.requestPermissions(this, permissionLists1.toArray(new String[permissionLists1.size()]), 1);
                    snackbar = SnackBarUtil.show(this, "获取拍摄照片和录制内容的权限说明：", "用于拍照和录制视频");
                } else if (permissionLists2.size() > 0) {
                    ActivityCompat.requestPermissions(this, permissionLists2.toArray(new String[permissionLists2.size()]), 5);
                    snackbar = SnackBarUtil.show(this, "获取麦克风和录制的权限说明：", "用于录制视频");
                } else if (permissionLists3.size() > 0) {
                    ActivityCompat.requestPermissions(this, permissionLists3.toArray(new String[permissionLists3.size()]), 6);
                    snackbar = SnackBarUtil.show(this, "获取您设备上的照片.媒体文件内容和文件的权限说明：", "用于储存照片和视频");
                } else if (permissionLists4.size() > 0) {
                    ActivityCompat.requestPermissions(this, permissionLists4.toArray(new String[permissionLists4.size()]), 7);
                    snackbar = SnackBarUtil.show(this, "获取您地理位置的权限说明：", "用于记录当前的位置");
                } else {
                    selectMedia(openAlbum, openRecordVideo, openVideoAlbum);
                }
            }
        } else {
            selectMedia(openAlbum, openRecordVideo, openVideoAlbum);
        }


    }

    //拍照和录像选择
    @Override
    public void takePhoto(String type, String max, String ownerObject, String ownerType, String ownerId, String takePicCallback, String offlineIsUploadImage,
                          String takePhotoOkCallback, String openAlbum,
                          String recordVideoCallback, String openRecordVideo, String openVideoAlbum, String uploadedCount
    ) {
        Log.e("shuchang", "h5---takePhoto-------6->");
        isDuoxuan = true;
        this.offlineIsUploadImage = offlineIsUploadImage;
        this.takePhotoType = type;
        this.takePicCallback = takePicCallback;
        this.ownerObject = ownerObject;
        this.ownerId = ownerId;
        this.ownerType = ownerType;
        this.canSelectNum = Integer.parseInt(max) - Integer.parseInt(uploadedCount);
        this.takePhotoOkCallback = takePhotoOkCallback;//拍照后图片在上传之前是否需要回调通知H5
        this.recordVideoCallback = recordVideoCallback;//拍照后图片在上传之前是否需要回调通知H5


        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
            //动态申请权限
            if (Build.VERSION.SDK_INT >= 23) {
                permissionLists1.clear();
                permissionLists2.clear();
                permissionLists3.clear();
                permissionLists4.clear();
                if (ContextCompat.checkSelfPermission(this, Manifest.permission.CAMERA) != PackageManager.PERMISSION_GRANTED) {
                    permissionLists1.add(Manifest.permission.CAMERA);
                }
                if (ContextCompat.checkSelfPermission(this, Manifest.permission.RECORD_AUDIO) != PackageManager.PERMISSION_GRANTED) {
                    permissionLists2.add(Manifest.permission.RECORD_AUDIO);
                }
                if (ContextCompat.checkSelfPermission(this, Manifest.permission.READ_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) {
                    permissionLists3.add(Manifest.permission.READ_EXTERNAL_STORAGE);
                }
                if (ContextCompat.checkSelfPermission(this, Manifest.permission.WRITE_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) {
                    permissionLists3.add(Manifest.permission.WRITE_EXTERNAL_STORAGE);
                }

                if (ContextCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
                    permissionLists4.add(Manifest.permission.ACCESS_FINE_LOCATION);
                }
                if (ContextCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
                    permissionLists4.add(Manifest.permission.ACCESS_COARSE_LOCATION);
                }
//                if (ContextCompat.checkSelfPermission(this, Manifest.permission.FOREGROUND_SERVICE) != PackageManager.PERMISSION_GRANTED) {
//                    permissionLists4.add(Manifest.permission.FOREGROUND_SERVICE);
//                }

                if (permissionLists1.size() > 0) {//说明肯定有拒绝的权限
                    ActivityCompat.requestPermissions(this, permissionLists1.toArray(new String[permissionLists1.size()]), 1);
                    snackbar = SnackBarUtil.show(this, "获取拍摄照片和录制内容的权限说明：", "用于拍照和录制视频");
                } else if (permissionLists2.size() > 0) {
                    ActivityCompat.requestPermissions(this, permissionLists2.toArray(new String[permissionLists2.size()]), 5);
                    snackbar = SnackBarUtil.show(this, "获取麦克风和录制的权限说明：", "用于录制视频");
                } else if (permissionLists3.size() > 0) {
                    ActivityCompat.requestPermissions(this, permissionLists3.toArray(new String[permissionLists3.size()]), 6);
                    snackbar = SnackBarUtil.show(this, "获取您设备上的照片.媒体文件内容和文件的权限说明：", "用于储存照片和视频");
                } else if (permissionLists4.size() > 0) {
                    ActivityCompat.requestPermissions(this, permissionLists4.toArray(new String[permissionLists4.size()]), 7);
                    snackbar = SnackBarUtil.show(this, "获取您地理位置的权限说明：", "用于记录当前的位置");
                } else {
                    selectMedia(openAlbum, openRecordVideo, openVideoAlbum);
                }
            }
        } else {
            selectMedia(openAlbum, openRecordVideo, openVideoAlbum);
        }


    }

    private void selectMedia(String openAlbum, String openRecordVideo, String openVideoAlbum) {
        final ShowMediaDialog showMediaDialog = new ShowMediaDialog(this, openAlbum, openRecordVideo, openVideoAlbum);
        showMediaDialog.setClicklistener(new ShowMediaDialog.ClickListenerInterface() {
            @Override
            public void takePhoto() {
                isDuoxuan = false;
                nativeTakePhoto();
                showMediaDialog.dismiss();
            }

            @Override
            public void selectAlubm() {
                if (isDuoxuan) {
                    openAblum(0);
                } else {
                    isDuoxuan = false;
                    Intent intent = new Intent(Intent.ACTION_PICK, null);
                    intent.setDataAndType(
                            MediaStore.Images.Media.EXTERNAL_CONTENT_URI,
                            "image/*");
                    startActivityForResult(intent, OPEN_ABLUM);
                }
                showMediaDialog.dismiss();
            }

            @Override
            public void recordVideo() {
                isDuoxuan = false;
                videoId = System.currentTimeMillis() + "" + (int) ((Math.random() * 9 + 1) * 100000);
                Intent intent = new Intent();
                intent.setClass(H5Activity.this, RecordVideoActivity.class);
                startActivityForResult(intent, RECORDVIDEO_H5);
                showMediaDialog.dismiss();
            }

            @Override
            public void selectVideo() {
                if (isDuoxuan) {
                    openAblum(1);
                } else {
                    isDuoxuan = false;
                    videoId = System.currentTimeMillis() + "" + (int) ((Math.random() * 9 + 1) * 100000);
                    Intent i = new Intent(Intent.ACTION_PICK, android.provider.MediaStore.Video.Media.EXTERNAL_CONTENT_URI);
                    startActivityForResult(i, ABLUM_VIDEO);
                }
                showMediaDialog.dismiss();
            }
        });
        showMediaDialog.show();
    }


    /**
     * 照片提示框
     */
    private void showAlbumDialog() {
        final AvatarSelectDialog avatarSelectDialog = new AvatarSelectDialog(this);
        avatarSelectDialog.show();
        avatarSelectDialog.setClicklistener(new AvatarSelectDialog.ClickListenerInterface() {
            @Override
            public void takePhoto() {//拍照
                if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
                    permissionLists10.clear();
                    permissionLists11.clear();
                    permissionLists12.clear();
                    permissionLists13.clear();
                    //动态申请权限
                    applyPermissions();

                    //1.拍摄照片和录制内容
                    //2。访问您设备上的照片。媒体文件内容和文件
                    //3。录制视频
                    //
//                    if (ContextCompat.checkSelfPermission(H5Activity.this, Manifest.permission.CAMERA) != PackageManager.PERMISSION_GRANTED) {
//                        permissionLists10.add(Manifest.permission.CAMERA);
//                    }
//
//                    if (ContextCompat.checkSelfPermission(H5Activity.this, Manifest.permission.RECORD_AUDIO) != PackageManager.PERMISSION_GRANTED) {
//                        permissionLists11.add(Manifest.permission.RECORD_AUDIO);
//                    }
//
//
//                    if (ContextCompat.checkSelfPermission(H5Activity.this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
//                        permissionLists12.add(Manifest.permission.ACCESS_FINE_LOCATION);
//                    }
//                    if (ContextCompat.checkSelfPermission(H5Activity.this, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
//                        permissionLists12.add(Manifest.permission.ACCESS_COARSE_LOCATION);
//                    }
//                    if (ContextCompat.checkSelfPermission(H5Activity.this, Manifest.permission.FOREGROUND_SERVICE) != PackageManager.PERMISSION_GRANTED) {
//                        permissionLists12.add(Manifest.permission.FOREGROUND_SERVICE);
//                    }
//
//
////            if (ContextCompat.checkSelfPermission(H5Activity.this, Manifest.permission.READ_PHONE_STATE) != PackageManager.PERMISSION_GRANTED) {
////                permissionLists13.add(Manifest.permission.READ_PHONE_STATE);
////            }
//                    if (ContextCompat.checkSelfPermission(H5Activity.this, Manifest.permission.WRITE_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) {
//                        permissionLists13.add(Manifest.permission.WRITE_EXTERNAL_STORAGE);
//                    }
//                    if (ContextCompat.checkSelfPermission(H5Activity.this, Manifest.permission.READ_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) {
//                        permissionLists13.add(Manifest.permission.READ_EXTERNAL_STORAGE);
//                    }
//
//                    if (permissionLists10.size() > 0) {
//                        ActivityCompat.requestPermissions(H5Activity.this, permissionLists10.toArray(new String[permissionLists10.size()]), 10);
//                    } else if (permissionLists11.size() > 0) {
//                        ActivityCompat.requestPermissions(H5Activity.this, permissionLists11.toArray(new String[permissionLists11.size()]), 11);
//                    } else if (permissionLists12.size() > 0) {
//                        ActivityCompat.requestPermissions(H5Activity.this, permissionLists12.toArray(new String[permissionLists12.size()]), 12);
//                    } else if (permissionLists13.size() > 0) {//说明肯定有拒绝的权限
//                        ActivityCompat.requestPermissions(H5Activity.this, permissionLists13.toArray(new String[permissionLists13.size()]), 13);
//                    } else {
//                        nativeTakePhoto();
//                    }


                } else {
                    nativeTakePhoto();
                }
                avatarSelectDialog.dismiss();
            }

            @Override
            public void selectAlubm() {//从相册选择
                Intent intent = new Intent(Intent.ACTION_PICK, null);
                intent.setDataAndType(
                        MediaStore.Images.Media.EXTERNAL_CONTENT_URI,
                        "image/*");
                startActivityForResult(intent, OPEN_ABLUM);
                avatarSelectDialog.dismiss();
            }
        });
    }


    /**
     * 扫码
     *
     * @param scanCallback
     */
    @Override
    public void openScan(String scanCallback) {
        this.scanCallback = scanCallback;
        applyPermissionsScan();

//        Intent intent = new Intent(context, CaptureActivity.class);
//        intent.putExtra("bletooth", "1");
//        startActivityForResult(intent, SCAN_CODE);
    }


    //返回
    @Override
    public void back() {
        KLog.e("执行");
//        finish();
//       AppManager.getAppManager().finishAllActivity();
    }

    /**
     * 跳转到登录界面
     */
    @Override
    public void gotoLogin() {
        Log.e("shuchang", "h5调用了去login页面的方法gotoLogin(),standard-->" + standard);
        if (standard) {
            startLogin();
        }
    }

    /**
     * 跳转到首页
     */
    @Override
    public void gotoIndex() {
        reloadWebview();
    }

    /**
     * 获取token
     *
     * @param getAccessTokenCallback
     */
    @Override
    public void getAccessToken(String getAccessTokenCallback) {
        Log.e("shuchang", "getAccessToken--->");
        this.getAccessTokenCallback = getAccessTokenCallback;
        Message msg = handler.obtainMessage(GET_ACCESSTOKEN_SUCCESS);
        msg.obj = UserHelper.getToken();
        msg.sendToTarget();
    }

    /**
     * 拨打电话
     *
     * @param phone
     */
    @Override
    public void callPhone(String phone) {
        Intent dialIntent = new Intent(Intent.ACTION_DIAL, Uri.parse("tel:" + phone));//跳转到拨号界面，同时传递电话号码
        startActivity(dialIntent);
    }

    /**
     * 下载文件
     *
     * @param downloadName 文件名称
     * @param downloadUrl  下载路径
     */
    @Override
    public void downloadFile(String downloadName, String downloadUrl, String downloadByte) {
        if (!downloadUrl.startsWith("http")) {
            downloadUrl = sharedPrefs.getString(Constant.BASE_ADDRESS_URL, "") + downloadUrl;
        }
        new DownloadFileManager().showDownloadDialog(context, downloadName, downloadUrl, downloadByte);
    }

    /**
     * 删除数据库和本地的离线图片
     *
     * @param id
     */
    @Override
    public void delPhoto(String id) {
        //如果有相同的图片ID，则删除该图片和在数据库中的图片信息
        List<Record> recordList = DBManager.getDBManager(this).getRecords(IMAGE.TABLE_NAME, null);
        for (Record record : recordList) {
            if (record.getString(Constant.TIMESTAMP).equals(id)) {
                Utility.deleteH5Image(context, record);
            }
        }

    }

    /**
     * 保存离线H5传过来的H5图片到本地和数据库，有网时候上传
     */
    @Override
    public void getBasePicture(String ownerObject, String ownerId, String ownerType, String base64) {
        String base64ImageName = ImageUtils.getImageName(this) + ".jpg";
        String filePath = ImageUtils.getH5ImagePath(base64ImageName, this);
        ImageUtils.base64ToImage(base64, filePath);
        //将base64保存到本地
        KLog.e(filePath);
        saveImageDataToDB(ownerId, ownerObject, ownerType, base64ImageName, System.currentTimeMillis());
    }

    /**
     * 离线数据是否上传
     *
     * @param judge 0代表没有数据上传，1代表有
     */
    @Override
    public void uploadedOfflineData(String judge) {
        XLog.i(judge + ":uploadedOfflineData");
        sharedPrefs.edit().putString(Constant.UPLOADED_OFFLINE_DATA, judge).apply();
    }

    //保存H5的log日志到本地文件夹
    @Override
    public void saveH5DebugLog(String level, String logs) {
        XLog.H5Log(level, logs, context);
    }

    //获取当前语言类型
    @Override
    public void getNativeCurrentLanguage(String currentLanguageCallback) {
        this.currentLanguageCallback = currentLanguageCallback;
        //设置H5的多语言
        handler.sendEmptyMessage(SET_CURRENT_LANGUAGE);
    }

    /**
     * 保存H5的数据到本地
     *
     * @param dataName                  数据名称
     * @param dataValue                 数据
     * @param saveH5DataToLocalCallBack 回调函数
     */
    @Override
    public void saveH5DataToLocal(String dataName, String dataValue, String saveH5DataToLocalCallBack) {
    }

    /**
     * 删除本地H5数据
     *
     * @param dataName 数据名称
     */
    @Override
    public void deleteH5DataForLocal(String dataName) {
    }

    /**
     * 获取H5数据
     *
     * @param dataName
     * @param getH5DataForLocalCallback
     */
    @Override
    public void getH5DataForLocal(String dataName, String uuid, String getH5DataForLocalCallback) {
    }

    //获取当前网络状态
    @Override
    public void getWorkStatus() {
        boolean available = NetworkUtils.isAvailable(this);
        if (available) {
//            handler.sendEmptyMessage(NETWORK_ONLINE);
            //有网的时候判断下是不是弱网
//            getNetworkState();
            if (networkMode.equals("1")) {
                handler.sendEmptyMessage(NETWORK_OFFLINE);
                Log.e("huohuohuohuo", "112233");
            } else {
                getNetworkState();
            }
        } else {
            handler.sendEmptyMessage(NETWORK_OFFLINE);
            Log.e("huohuohuohuo", "112244");
        }
    }

    /**
     * 刷新webview
     */
    @Override
    public void reloadWebview() {
        handler.sendEmptyMessage(RELOAD_URL);

    }

    /**
     * 打开个人信息界面
     */
    @Override
    public void openPresionInfoActivity() {
        Intent intent = new Intent();
        intent.setClass(this, PresionInfoActivity.class);
        startActivity(intent);
    }


    @Override
    public void getLongAndLat(String gpsCallback) {
        Log.e("shuchang", "--->getLongAndLat");
        this.gpsCallback = gpsCallback;
        handler.sendEmptyMessage(GET_LOCATION_SUCCESS);
    }

    GPSBean bean = new GPSBean();
    Gson gson = new Gson();

    @Override
    public void getCurrentTimeLongAndLat(String gpsCallback) {
        Log.e("shuchang", "--->getCurrentTimeLongAndLat");
        this.gpsSlhishiCallback = gpsCallback;
        initShiahiLocation();
    }

    @Override
    public void setBadgeNumber(int number) {
        Log.e("shuchang", "--->setBadgeNumber--->" + number);
        JPushInterface.setBadgeNumber(context, number);
    }

    /**
     * 设置当前是离线还是在线模式
     */
    @Override
    public void setNetworkMode(String networkMode) {
        this.networkMode = networkMode;
        sharedPrefs.edit().putString(Constant.OPEN_OFFLINE_MODE, networkMode).apply();
        if (networkMode.equals("1")) {
            isOnline = false;
            handler.sendEmptyMessage(NETWORK_OFFLINE);
            Log.e("huohuohuohuo", "112255");
            EventBus.getDefault().post(new NetworkListEvent(0));
        } else {
            isOnline = true;
            EventBus.getDefault().post(new NetworkListEvent(1));
            handler.sendEmptyMessage(NETWORK_ONLINE);
        }
    }


    @Override
    public void initCallback(String result) {
        initHtmleCallbackResult = result;
    }

    /**
     * 打开NFC界面.
     *
     * @param nfcCallback
     */
    @Override
    public void openNfc(String nfcCallback) {
        this.nfcCallback = nfcCallback;
        Intent intent = new Intent(context, H5ForNfcActivity.class);
        intent.putExtra(Constant.SCAN_TO_OPEN_NFC, false);
        startActivity(intent);
    }

    @Override
    public void getWifiStatus(String wifiCallbacks) {
        wifiCallback = wifiCallbacks;
        Message msg = handler.obtainMessage(WIFI_STATUS);
        if (NetworkUtils.isWifi(context)) {
            msg.obj = "0";
        } else {
            msg.obj = "1";
        }
        msg.sendToTarget();
    }

    /**
     * 打开流媒体播放界面.
     *
     * @param rtmpId
     * @param rtmpName
     * @param rtmpType
     * @param rtmpAddress
     * @param rtmpStatus
     * @param rtmpUrl
     */
    @Override
    public void openRtmpVideoActivity(String rtmpId, String rtmpName, String rtmpType, String rtmpAddress, String rtmpStatus, String rtmpUrl) {
//        //刷新流媒体数据
//        webView.evaluateJavascript("javascript:getRtmpStatus()", new ValueCallback<String>() {
//            @Override
//            public void onReceiveValue(String value) {
//                //此处为 js 返回的结果
//            }
//        });
        Intent intent = new Intent();
        intent.putExtra("rtmpId", rtmpId);
        intent.putExtra("rtmpName", rtmpName);
        intent.putExtra("rtmpType", rtmpType);
        intent.putExtra("rtmpAddress", rtmpAddress);
        intent.putExtra("rtmpStatus", rtmpStatus);
        intent.putExtra("rtmpUrl", rtmpUrl);
        intent.setClass(this, RtmpVideoActivity.class);
        startActivity(intent);

    }

    @Override
    public void isShowHomeBack(String showHomeBackCallback) {
        this.isShowHomeBackCallback = showHomeBackCallback;
        Message msg = handler.obtainMessage(IS_SHOW_HOME_BACK);
        msg.sendToTarget();
    }

    @Override
    public void openExternalBrowser(String url) {
        Intent intent = new Intent();
        // 设置意图动作为打开浏览器
        intent.setAction(Intent.ACTION_VIEW);
        // 声明一个Uri
        Uri uri = Uri.parse(url);
        intent.setData(uri);
        context.startActivity(intent);
    }

    @Override
    public void openShare(String url) {
        Intent shareIntent = new Intent();
        shareIntent.setAction(Intent.ACTION_SEND);
        shareIntent.setType("text/plain");
        shareIntent.putExtra(Intent.EXTRA_TEXT, url);
//切记需要使用Intent.createChooser，否则会出现别样的应用选择框，您可以试试
        shareIntent = Intent.createChooser(shareIntent, "分享到");
        context.startActivity(shareIntent);


    }


    @Override
    public void openShare(String title, String url) {
        Intent shareIntent = new Intent();
        shareIntent.setAction(Intent.ACTION_SEND);
        shareIntent.setType("text/plain");
        shareIntent.putExtra(Intent.EXTRA_TEXT, url);
        shareIntent.putExtra(Intent.EXTRA_TITLE, title);
//切记需要使用Intent.createChooser，否则会出现别样的应用选择框，您可以试试
        shareIntent = Intent.createChooser(shareIntent, "分享到");
        context.startActivity(shareIntent);


    }

    @Override
    public void openShareAddTitle(String title, String url) {
        Intent shareIntent = new Intent();
        shareIntent.setAction(Intent.ACTION_SEND);
        shareIntent.setType("text/plain");
        shareIntent.putExtra(Intent.EXTRA_TEXT, url);
        shareIntent.putExtra(Intent.EXTRA_TITLE, title);
//切记需要使用Intent.createChooser，否则会出现别样的应用选择框，您可以试试
        shareIntent = Intent.createChooser(shareIntent, "分享到");
        context.startActivity(shareIntent);
    }

    @Override
    public void getStatusBar(String callBack) {
        getStatusBarCallBack = callBack;
        handler.sendEmptyMessage(10000);
    }

    @Override
    public void changStatusBarColor(int color) { //0：白色。1:深色
        Message message = handler.obtainMessage(10001);
        Bundle bundle = new Bundle();
        bundle.putInt("color", color);
        message.obj = bundle;
        handler.sendMessage(message);
    }

    @Override
    public void getNoUploadFileNum(String callback1) {
        getNoUploadFileNumCallback = callback1;
        handler.sendEmptyMessage(10005);
    }

    @Override
    public void startUploadFile(String callback2) {
        startUploadFileCallback = callback2;
        handler.sendEmptyMessage(10006);
    }


    @Override
    public void startBatchUploadFile(String callback2) {
        handler.sendEmptyMessage(3000);
        //Log.e("1111333", "startBatchUploadFile");
    }

    @Override
    public void showNativeInspectionDetial(String str) {
        Log.e("shuchang", "h5给showNativeInspectionDetial的json---->" + str);
        Message message = handler.obtainMessage(SHOW_NATIVE_INSPECTION_DETAIL);
        message.obj = str;
        handler.sendMessage(message);
    }

    @Override
    public void downLoadInspection(String json) {
        Message message = handler.obtainMessage(DOWN_LOAD_INSPECTION);
        message.obj = json;
        handler.sendMessage(message);
    }

    @Override
    public void backNativeLastPage() {
        if (!FastClickHelper.isFastClick()) return;
        KLog.e("kangwenjing", "huohuohuohuo11111111111");
        if (Constant.isBao) {
            KLog.e("kangwenjing", "huohuohuohuo11111111111");
            if (AppManager.isActivityExist(StartWorkActivity.class)) {
                KLog.e("222222");
                Intent intent = new Intent(context, StartWorkActivity.class);
                intent.setFlags(Intent.FLAG_ACTIVITY_REORDER_TO_FRONT);
                context.startActivity(intent);
                overridePendingTransition(R.anim.slide_out_left, R.anim.slide_in_right);
                KLog.e("222222");
            } else if (AppManager.isActivityExist(CheckDetailsActivity.class)) {
                KLog.e("222222");
                Intent intent = new Intent(context, CheckDetailsActivity.class);
                intent.setFlags(Intent.FLAG_ACTIVITY_REORDER_TO_FRONT);
                context.startActivity(intent);
                overridePendingTransition(R.anim.slide_out_left, R.anim.slide_in_right);
                KLog.e("222222");
            }
            if (webView.canGoBack()) {
                KLog.e("kangwenjing", "huohuohuohuo2222222222222");
                webView.goBack();
            }
            EventBus.getDefault().post(new StartH5Event(reJson));
            reJson = "";
            //Constant.isBao=false;
            // onBackPressed();
        } else {
            EventBus.getDefault().post(new StartH5Event(reJson));
            reJson = "";
            finish();
        }
    }

    @Override
    public void reportOrderSuccess(String json) {
        //通知startWorkActivity
//        Intent intent = new Intent();
//        intent.putExtra("json", json);
//        setResult(RESULT_OK, intent);
        //
        reJson = json;
        EventBus.getDefault().post(new StartH5Event(json));
        reJson = "";
        KLog.e(1111);
        backNativeLastPage();


    }


    private String reJson;
    private String statusCall;

    @Override
    public void getInspOfflineTaskStatus(String call) {
        statusCall = call;
        handler.sendEmptyMessage(988);
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onMessageEvent(UploadEventLoad event) {
        if (handler != null) {
            handler.sendEmptyMessage(987);
        }
    }


    /**
     * 上传图片到PC端成功
     *
     * @param baseData
     */
    @Override
    public void uploadImgForClientSuccess(UploadImage baseData, String thumburl) {
        Log.e("shuchang", "上传结束--->" + System.currentTimeMillis());
        if (loadingDialog != null) {
            loadingDialog.dismiss();
        }
        //上传成功后删除该图片
        FileUtil.deleteOneFile(ImageUtils.getH5ImagePath(thumburl, this));
        //上传成功后组装集合回调数据给H5
        sendJsonToH5(presenter.getUploadImageSuccessList(baseData));
    }

    /**
     * 上传图片到PC端失败或者仅WIFI和离线上传
     * param 有网图片上传失败时code传0，设置了仅wifi或者没有网络时候离线上传code为2
     */
    @Override
    public void uploadImgForClientOnError(int code, String imaName) {
        try {
            if (loadingDialog != null) {
                loadingDialog.dismiss();
            }
            Log.e("shuchang", "上传结束--->" + System.currentTimeMillis());
            //上传base64图片
            String result = FileUtil.encodeBase64FileToThumToH5(imaName, this);
            //图片大小
            long fileSize = FileUtil.getFileSize(ImageUtils.getH5ImageThumPath(imaName, this));
            Message msg = handler.obtainMessage(TAKEPIC_SUCCESS);
            //获取当前的时间戳，用来作为该图片的唯一识别，方便H5长按删除本地的该图片
            long timeStamp = System.currentTimeMillis();
            Bundle bundle = new Bundle();
//            bundle.putString(Constant.BASE64_RESULT, result);
            bundle.putString(Constant.BASE64_RESULT, "");
            bundle.putLong(Constant.BASE64_FILESIZE, fileSize);
            bundle.putString(Constant.UPLOAD_IAMGE_NAME, imaName);
            bundle.putInt(Constant.BASE64_CODE, code);
            bundle.putLong(Constant.TIMESTAMP, timeStamp);
            msg.obj = bundle;
            msg.sendToTarget();
            //保存图片信息到数据库，APP有网络时在批量上传图片
            if (offlineIsUploadImage.equalsIgnoreCase("true")) {
                saveImageDataToDB(ownerId, ownerObject, ownerType, imaName, timeStamp);
            } else {
                //如果不保存就删除这个图片
                Utility.deleteH5ImageNotUpload(imaName, this);
            }
        } catch (Exception e) {
        }
    }

    @Override
    public void uploadImgOrVideoEnd() {
        if (isDuoxuan) {
            hasUploadCount++;
            if (hasUploadCount == uploadCount) {
                isDuoxuan = false;
                Log.e("shuchang", "上传完成--->" + uploadCount);
                ToastMessage(getResources().getString(R.string.upload_success));
                hideLoading();
            }
        } else {
            ToastMessage(getResources().getString(R.string.upload_success));
            hideLoading();
        }
    }

    /**
     * 保存图片信息到数据库
     *
     * @param ownerId     图片ID
     * @param ownerObject 图片类型
     * @param ownerType   上传的方式
     * @param imagName    图片名称
     * @param timeStamp   时间戳
     */
    public void saveImageDataToDB(String ownerId, String ownerObject, String ownerType, String imagName, long timeStamp) {
        try {
            EventBus.getDefault().post(new HandleJsEvent(3002, ownerId));
            DBManager dbManager = DBManager.getDBManager(context);
            db = dbManager.getDB();
            db.beginTransaction();
            Record record = new Record(IMAGE.TABLE_NAME);
            record.setValue(IMAGE.OWNERID, ownerId);
            record.setValue(IMAGE.OWNEROBJECT, ownerObject);
            record.setValue(IMAGE.OWNERTYPE, ownerType);
            record.setValue(IMAGE.IMAGEURL, imagName);
            record.setValue(IMAGE.TIMESTAMP, imagName.split("\\.")[0]);
            dbManager.insert(record);
            db.setTransactionSuccessful();
        } catch (Exception e) {
        } finally {
            if (db != null) {
                db.endTransaction();
            }
        }
    }

    /**
     * 获取token成功
     *
     * @param cookieToken
     */
    @Override
    public void getAccessTokenSuccess(String cookieToken) {
//        Message msg = handler.obtainMessage(GET_ACCESSTOKEN_SUCCESS);
//        msg.obj = cookieToken;
//        msg.sendToTarget();
    }

    /**
     * 获取token失败
     */
    @Override
    public void getAccessTokenOnError() {
//        startLogin();
    }

    @Override
    public void openSmallVideo(String networkUrl) {
        Intent intent = new Intent();
        intent.putExtra("url", networkUrl);
        intent.setClass(this, MediaSurfaceActivity.class);
        startActivity(intent);
    }

    @Override
    public void setAvatarAuth(String isShowAvatar) {
        //设置是否显示头像
        sharedPrefs.edit().putString(Constant.ISSHOWAVATAR, isShowAvatar).apply();
    }

    /**
     * 上传视频成功
     *
     * @param url
     */
    @Override
    public void uploadVideoSuccess(String url, String localUrl, String id) {
        UploadVideDataBean videDataBean = presenter.getUploadVideoSuccessList("视频上传成功", url, localUrl, id, ownerId, ownerObject, ownerType);
        Gson gson = new Gson();
        String s = gson.toJson(videDataBean);
        Message msg = handler.obtainMessage(RECORD_VIDEO_FOR_URL_SUCCESS);
        Bundle bundle = new Bundle();
        bundle.putString("json", s);
        msg.obj = bundle;
        msg.sendToTarget();
        ToastMessage(getResources().getString(R.string.upload_success));
    }

    /**
     * 上传视频失败
     *
     * @param localUrl
     */
    @Override
    public void uploadVideoError(String localUrl, String id) { //以前id为-1
        UploadVideDataBean videDataBean = presenter.getUploadVideoSuccessList("视频上传失败", "", localUrl, id, ownerId, ownerObject, ownerType);
        Gson gson = new Gson();
        String s = gson.toJson(videDataBean);
        Message msg = handler.obtainMessage(RECORD_VIDEO_FOR_URL_SUCCESS);
        Bundle bundle = new Bundle();
        bundle.putString("json", s);
        msg.obj = bundle;
        msg.sendToTarget();
        ToastMessage(getResources().getString(R.string.upload_failure));
        try {
            DBManager dbManager = DBManager.getDBManager(context);
            db = dbManager.getDB();
            db.beginTransaction();
            Record record = new Record(VIDEO.TABLE_NAME);
            record.setValue(VIDEO.OWNERID, ownerId);
            record.setValue(VIDEO.OWNEROBJECT, ownerObject);
            record.setValue(VIDEO.OWNERTYPE, ownerType);
            record.setValue(VIDEO.VIDEOURL, "");
            record.setValue(VIDEO.VIDEOLOCALURL, localUrl);
            record.setValue(VIDEO.TIMESTAMP, videoId);
            dbManager.insert(record);
            db.setTransactionSuccessful();


        } catch (Exception e) {
            XLog.i(e.getMessage());
        } finally {
            if (db != null) {
                db.endTransaction();
            }
        }
    }


    /**
     * 去登陆界面
     */
    private void startLogin() {
        hideLoading();
        /**删除权限，系统设置和用户信息*/
        Log.e("shuchang", "tologin--->startLogin");
        Utility.startLoginActivity(context);
    }


    /**
     * 发送json数据通知H5
     *
     * @param photoUploadBean
     */
    private void sendJsonToH5(PhotoUploadBean photoUploadBean) {
        photoUploadBean.setOwnerId(ownerId);
        photoUploadBean.setOwnerType(ownerType);
        photoUploadBean.setOwnerObject(ownerObject);
        Gson gson = new Gson();
        String s = gson.toJson(photoUploadBean);
        Message msg = handler.obtainMessage(TAKEPIC_FOR_URL_SUCCESS);
        Bundle bundle = new Bundle();
        bundle.putString("json", s);
        msg.obj = bundle;
        msg.sendToTarget();
    }

    private View mCustomView;    //用于全屏渲染视频的View
    private IX5WebChromeClient.CustomViewCallback mCustomViewCallback;
    private android.webkit.ValueCallback<Uri> uploadMessage;
    private android.webkit.ValueCallback<Uri[]> uploadMessageAboveL;

    public class WebChromeClient extends com.tencent.smtt.sdk.WebChromeClient {

        @Override
        public void onProgressChanged(WebView view, int newProgress) {
            //监听页面加载进度
            if (newProgress == 100) {
                //网页加载完成后在加载图片
                webView.getSettings().setBlockNetworkImage(false);
//                    hideLoading();
            }
            super.onProgressChanged(view, newProgress);
        }

        @Override
        public boolean onShowFileChooser(WebView webView, ValueCallback<Uri[]> valueCallback, FileChooserParams fileChooserParams) {
            uploadMessageAboveL = valueCallback;
            uploadPicture();
            return true;

        }

        @Override
        public void onShowCustomView(View view, IX5WebChromeClient.CustomViewCallback customViewCallback) {
            super.onShowCustomView(view, customViewCallback);
//            if (mCustomViewCallback != null) {
//                mCustomViewCallback.onCustomViewHidden();
//                mCustomViewCallback = null;
//                return;
//            }
//            getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN);
//            ViewGroup parent = (ViewGroup) webView.getParent().getParent();
//            parent.setVisibility(View.GONE);
//            ((ViewGroup) parent.getParent()).addView(view, new ViewGroup.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT));
//            mCustomView = view;
//            mCustomViewCallback = customViewCallback;


            if (mCustomView != null) {
                customViewCallback.onCustomViewHidden();
                return;
            }
            mCustomView = view;
            // 获取当前View的LayoutParams
//            FrameLayout.LayoutParams params = new FrameLayout.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT);
//
//            // 设置新的宽度和高度
//            params.width = ScreenUtils.getScreenHeight(H5Activity.this);
//            params.height = ScreenUtils.getScreenWidth(H5Activity.this);

            webFramlayout.addView(mCustomView);
            mCustomViewCallback = customViewCallback;
            webView.setVisibility(View.GONE);
//            setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE);
        }

        /**
         * 解决WebView播放视频点击全屏按钮白屏的问题。
         * ps：如果去掉则部分机型视频全屏展示时有问题
         */
        @Override
        public void onHideCustomView() {
            super.onHideCustomView();
//            if (mCustomView != null) {
//                if (mCustomViewCallback != null) {
//                    mCustomViewCallback.onCustomViewHidden();
//                    mCustomViewCallback = null;
//                }
//                getWindow().clearFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN);
//
//                if (mCustomView != null && mCustomView.getParent() != null) {
//                    ViewGroup parent = (ViewGroup) mCustomView.getParent();
//                    parent.removeView(mCustomView);
//
//                    if (webView.getParent().getParent() != null) {
//                        ViewGroup parent2 = (ViewGroup) webView.getParent().getParent();
//                        parent2.setVisibility(View.VISIBLE);
//                    }
//                }
//                mCustomView = null;
//            }
            webView.setVisibility(View.VISIBLE);
            if (mCustomView == null) {
                return;
            }
            mCustomView.setVisibility(View.GONE);
            webFramlayout.removeView(mCustomView);
            mCustomViewCallback.onCustomViewHidden();
            mCustomView = null;
            setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
            super.onHideCustomView();
        }
    }

    @Override
    public void onConfigurationChanged(Configuration config) {
        super.onConfigurationChanged(config);
        switch (config.orientation) {
            case Configuration.ORIENTATION_LANDSCAPE:
                getWindow().clearFlags(WindowManager.LayoutParams.FLAG_FORCE_NOT_FULLSCREEN);
                getWindow().addFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN);
                break;
            case Configuration.ORIENTATION_PORTRAIT:
                getWindow().clearFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN);
                getWindow().addFlags(WindowManager.LayoutParams.FLAG_FORCE_NOT_FULLSCREEN);
                break;
        }
    }

    /**
     * 拍照
     */
    public void nativeTakePhoto() {

        //获取一次定位
        getGps();

        imageName = ImageUtils.getImageName(this) + ".jpg";
        //三星手机用自己CameraActivity相机拍照防止崩溃bug
//        if (Build.BRAND.equalsIgnoreCase("samsung")){
        if (Build.BRAND.equalsIgnoreCase("nokia")) {
            Utility.startPhotoActivityForH5(H5Activity.this, TAKEPIC_H5, ImageUtils.getH5ImagePath(imageName, context));
        } else {
            Intent intent = new Intent(this, CameraOneActivity.class);
            intent.putExtra("imagename", imageName);
            startActivityForResult(intent, TAKEPIC_H5);
            overridePendingTransition(0, 0);
        }
//        }else {
        // 其他型号用原生的就可以
//            Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
//            intent.putExtra("android.intent.extras.CAMERA_FACING", Camera.CameraInfo.CAMERA_FACING_BACK);
//            intent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(new File(ImageUtils.getH5ImagePath(imageName))));
//            startActivityForResult(intent, TAKEPIC_H5);
//        }

    }


    //界面销毁时保存数据
    @Override
    protected void onSaveInstanceState(Bundle outState) {
        outState.putString("imageName", imageName);
        XLog.i("onSaveInstanceState---" + imageName, context);
        super.onSaveInstanceState(outState);

    }

    private int uploadCount = 0;  // 多图多视频上传的数目
    private int hasUploadCount = 0;  // 当前上传完了第几个

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == TAKEPIC_H5) {
            //打开图片编辑页面
            //h5拍照,拍照成功返回结果是-1
            if (resultCode == -1) {
                Intent intent = new Intent(this, ImageEditActivity.class);
                intent.putExtra("imageName", imageName);
                intent.putExtra("locationDescribe", locationDescribe);
                intent.putExtra("intentType", 0);
                startActivityForResult(intent, IMAGEEDIT_OK);
            }

        } else if (requestCode == SCAN_CODE) {
            if (data != null) {
                //上传扫码结果
                String result = data.getStringExtra(CaptureActivity.SCAN_RESULT);
                String assetno;
                //如果在扫码界面选择手动选择，进入设备查询界面通过设备扫码，就不用重复记录扫码操作了
                if (data.getBooleanExtra("isscan", false)) {
                    assetno = result;
                } else {
                    assetno = Utility.getScanCode(result);
                }
                Message msg = handler.obtainMessage(SCAN_SUCCESS);
                msg.obj = assetno;
                msg.sendToTarget();
            }
        } else if (requestCode == IMAGEEDIT_OK) {
            if (resultCode == Constant.EDITIMAGE_OK) {
                //如果需要拍照后立即回调，先调用这个方法，
//                if (!TextUtils.isEmpty(takePhotoOkCallback)) {

                String pathuri = data.getStringExtra("pathuri");
                takePhotoEditImageOkCallBack(pathuri);
//                }
                handleTakePic();
            } else {
                //用户点了回退，删除刚拍照过的图片
                FileUtil.deleteOneFile(ImageUtils.getH5ImagePath(imageName, this));
            }
        } else if (requestCode == OPEN_ABLUM) {
            if (data == null) {
                return;
            }
            imageName = ImageUtils.getImageName(this) + ".jpg";
            Uri selectedImage = data.getData(); //获取系统返回的照片的Uri
            if (selectedImage == null) {
                return;
            }
//            String[] filePathColumn = {MediaStore.Images.Media.DATA};
//            Cursor cursor = getContentResolver().query(selectedImage,
//                    filePathColumn, null, null, null);//从系统表中查询指定Uri对应的照片
//            cursor.moveToFirst();
//            int columnIndex = cursor.getColumnIndex(filePathColumn[0]);
//            String path = cursor.getString(columnIndex);  //获取照片路径
//            cursor.close();
//            Bitmap bitmap = BitmapFactory.decodeFile(path);

            BitmapUtils.saveJPGE_After(context, BitmapUtils.uriToBitmap(this, selectedImage),
                    imageName, 100);


            Intent intent = new Intent(this, ImageEditActivity.class);
            intent.putExtra("imageName", imageName);
            intent.putExtra("locationDescribe", locationDescribe);
            intent.putExtra("intentType", 1);
            startActivityForResult(intent, IMAGEEDIT_OK);
        } else if (requestCode == RECORDVIDEO_H5) {
            if (data != null) {
                //录制视频返回的url
                String url = data.getStringExtra(Constant.RECORD_VIDEO_OK);
                takePhotoEditVideoOkCallBack(videoId);
                uploadVideo(url, videoId);
            }
        } else if (requestCode == ABLUM_VIDEO) {
            if (data == null) {
                return;
            }
            Uri selectedVideo = data.getData();
            if (selectedVideo == null) {
                return;
            }
            String[] filePathColumn = {MediaStore.Video.Media.DATA};
            Cursor cursor = getContentResolver().query(selectedVideo,
                    filePathColumn, null, null, null);
            cursor.moveToFirst();
            int columnIndex = cursor.getColumnIndex(filePathColumn[0]);
            String VIDEOPATH = cursor.getString(columnIndex);
            cursor.close();


            MediaMetadataRetriever mmr = new MediaMetadataRetriever();
            mmr.setDataSource(VIDEOPATH);
            if (TextUtils.isEmpty(mmr.extractMetadata(MediaMetadataRetriever.METADATA_KEY_DURATION))) {
                ToastUtils.showShort(this, getResources().getString(R.string.Record_time_short));
                return;
            }
            int duration = Integer.parseInt(mmr.extractMetadata(MediaMetadataRetriever.METADATA_KEY_DURATION));
            if (duration >= 1000 * 11) {
                ToastUtils.showShort(this, getResources().getString(R.string.video_long_time));
                return;
            }
            takePhotoEditVideoOkCallBack(videoId);
            uploadVideo(VIDEOPATH, videoId);
        }


        //取消拍照或者图片选择时
        else if (resultCode != RESULT_OK) {
            //一定要返回null,否则<input file> 就是没有反应
            if (uploadMessage != null) {
                uploadMessage.onReceiveValue(null);
                uploadMessage = null;
            }
            if (uploadMessageAboveL != null) {
                uploadMessageAboveL.onReceiveValue(null);
                uploadMessageAboveL = null;
            }
        } else if (requestCode == REQUEST_SELECT_IMAGES_CODE && resultCode == RESULT_OK) {
            mediaFiles = (List<MediaFile>) data.getSerializableExtra(ImagePicker.EXTRA_SELECT_IMAGES);
            Log.e("shuchang", "duoxuan_to_h5_time---->" + System.currentTimeMillis());
            Message message = handler.obtainMessage(10002);
            Bundle bundle = new Bundle();
            bundle.putSerializable("mediaFiles", (Serializable) mediaFiles);
            message.obj = bundle;
            handler.sendMessage(message);
        }

//拍照成功和选取照片时
        if (resultCode == RESULT_OK) {
            if (requestCode != REQUEST_SELECT_IMAGES_CODE) {
                Uri imageUri = null;

                switch (requestCode) {
                    case REQUEST_CODE_ALBUM:

                        if (data != null) {
                            imageUri = data.getData();
                        }

                        break;
                    case REQUEST_CODE_CAMERA:

                        if (!TextUtils.isEmpty(mCurrentPhotoPath)) {
                            File file = new File(mCurrentPhotoPath);
                            Uri localUri = Uri.fromFile(file);
                            Intent localIntent = new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE, localUri);
                            sendBroadcast(localIntent);
                            imageUri = Uri.fromFile(file);
                            mLastPhothPath = mCurrentPhotoPath;
                        }
                        break;
                }


                //上传文件
                if (uploadMessage != null) {
                    uploadMessage.onReceiveValue(imageUri);
                    uploadMessage = null;
                }
                if (uploadMessageAboveL != null) {
                    uploadMessageAboveL.onReceiveValue(new Uri[]{imageUri});
                    uploadMessageAboveL = null;

                }
            }

        }


    }


    public void uploadVideo(final String localUrl, String ids) {
        File files = new File(localUrl);
        if (!files.exists()) {
            return;
        }
//        loadingDialog.setText(getResources().getString(R.string.uploading));
//        showLoading();
        presenter.uploadVideo(localUrl, ids, files);
    }

    //拍照成功后先回调通知H5
    private void takePhotoEditImageOkCallBack(String editpath) {
        try {
            String result = FileUtil.encodeBase64FileToThumToH5(imageName, this);
            //图片大小
            long fileSize = FileUtil.getFileSize(ImageUtils.getH5ImageThumPath(imageName, H5Activity.this));
            Log.e("HttpLogging1", "拍照成功之后的图片long--->" + fileSize);
//            String localPath = FileUtil.getLocalImageUri(H5Activity.this, editpath);
            Log.e("HttpLogging2", "拍照成功之后的图片地址--->" + editpath);
            Message msg = handler.obtainMessage(TAKEPHOTO_EDITIMAGE_SUCCESS);
            //获取当前的时间戳，用来作为该图片的唯一识别，方便H5长按删除本地的该图片
            long timeStamp = System.currentTimeMillis();
            Bundle bundle = new Bundle();
            bundle.putString(Constant.BASE64_RESULT, result);
            bundle.putLong(Constant.BASE64_FILESIZE, fileSize);
            bundle.putInt(Constant.BASE64_CODE, 2);
            bundle.putLong(Constant.TIMESTAMP, timeStamp);
//            bundle.putString(Constant.UPLOAD_IAMGE_LOCAL_PATH, editpath);
            msg.obj = bundle;
            msg.sendToTarget();
        } catch (Exception e) {
            e.printStackTrace();
        }

    }


    //拍照成功后先回调通知H5多选
    private void takePhotoEditImageOkCallBackWanzheng(final String imaname) {
        new Thread(new Runnable() {
            @Override
            public void run() {
                //上传base64图片
                try {
                    Log.e("shuchang", "图片压缩开始2--->" + System.currentTimeMillis());
                    FileUtil.encodeBase64FileToThumToH5Listener(imaname, H5Activity.this, new OnDialogStringListener() {
                        @Override
                        public void onDialogSureListener(String result) {
                            long fileSize = FileUtil.getFileSize(ImageUtils.getH5ImageThumPath(imaname, H5Activity.this));
                            Log.e("shuchang", "图片压缩结束2--->" + System.currentTimeMillis());
                            Log.e("HttpLogging", "拍照成功之后的图片long--->" + fileSize);
                            Log.e("shuchang", "给h5--imaname->" + imaname);
                            Message msg = handler.obtainMessage(TAKEPHOTO_EDITIMAGE_SUCCESS);
                            //获取当前的时间戳，用来作为该图片的唯一识别，方便H5长按删除本地的该图片
                            long timeStamp = System.currentTimeMillis();
                            Bundle bundle = new Bundle();
                            bundle.putString(Constant.BASE64_RESULT, result);
                            bundle.putString(Constant.UPLOAD_IAMGE_NAME, imaname);
                            bundle.putLong(Constant.BASE64_FILESIZE, fileSize);
                            bundle.putInt(Constant.BASE64_CODE, 2);
                            bundle.putLong(Constant.TIMESTAMP, timeStamp);
                            msg.obj = bundle;
                            msg.sendToTarget();
                        }
                    });
                    //图片大小

                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }).start();

    }

    //录制视频成功后先回调通知H5
    private void takePhotoEditVideoOkCallBack(String vId) {
        try {
            Message msg = handler.obtainMessage(TAKEPHOTO_EDITVIDEO_SUCCESS);
            //获取当前的时间戳，用来作为该图片的唯一识别，方便H5长按删除本地的该图片
            long timeStamp = System.currentTimeMillis();
            Bundle bundle = new Bundle();
            bundle.putInt(Constant.BASE64_CODE, 2);
            bundle.putString("videoId", vId);
            bundle.putLong(Constant.TIMESTAMP, timeStamp);
            msg.obj = bundle;
            msg.sendToTarget();
        } catch (Exception e) {
            e.printStackTrace();
        }

    }

    public void handleTakePic() {
//        handler.sendEmptyMessage(SHOW_DIALOG);
        new Thread(new Runnable() {
            @Override
            public void run() {
                try {
                    String result;
                    if (takePhotoType.equals(Constant.UPLOAD_IMAGE_BASE64)) {
                        //上传base64图片
                        result = FileUtil.encodeBase64FileToThumToH5(imageName, H5Activity.this);
                        //图片大小
                        long fileSize = FileUtil.getFileSize(ImageUtils.getH5ImageThumPath(imageName, H5Activity.this));
                        Message msg = handler.obtainMessage(TAKEPIC_SUCCESS);
                        Bundle bundle = new Bundle();
                        bundle.putString(Constant.BASE64_RESULT, result);
                        bundle.putLong(Constant.BASE64_FILESIZE, fileSize);
                        bundle.putInt(Constant.BASE64_CODE, 2);
                        msg.obj = bundle;
                        msg.sendToTarget();
                    } else {
                        //判断是否有网络，如果没有则直接离线上传
                        if (NetworkUtils.isAvailable(context)) {
                            //判断用户是否为仅wifi情况下上传图片,如果不是wifi则视为离线上传
                            boolean wifi_up = sharedPrefs.getBoolean(Constant.WIFI_UP, false);
                            if (wifi_up) {
                                if (!NetworkUtils.isWifi(context)) {
                                    //图片保存到数据库，有wifi时候在上传
                                    uploadImgForClientOnError(2, imageName);
                                } else {
                                    //上传图片到客户端
                                    sendUploadToHandler(imageName);
                                }
                            } else {
                                //上传图片到客户端
                                sendUploadToHandler(imageName);
                            }
                        } else {
                            uploadImgForClientOnError(2, imageName);
                        }
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                    //如果没有图片的话隐藏dialog
                    handler.sendEmptyMessage(HIDE_DIALOG);
                }
            }
        }).start();
    }

    public void handleTakePicWanzheng(final String path) {
        new Thread(new Runnable() {
            @Override
            public void run() {
                try {
                    String result;
                    if (takePhotoType.equals(Constant.UPLOAD_IMAGE_BASE64)) {

                        Log.e("shuchang", "图片压缩开始3--->" + System.currentTimeMillis());

                        //上传base64图片
                        result = FileUtil.encodeBase64FileToThumToH5(path, H5Activity.this);
                        //图片大小
                        long fileSize = FileUtil.getFileSize(ImageUtils.getH5ImageThumPath(path, H5Activity.this));

                        Log.e("shuchang", "图片压缩结束3--->" + System.currentTimeMillis());

                        Message msg = handler.obtainMessage(TAKEPIC_SUCCESS);
                        Bundle bundle = new Bundle();
                        bundle.putString(Constant.BASE64_RESULT, result);
                        bundle.putString(Constant.UPLOAD_IAMGE_NAME, path);
                        bundle.putLong(Constant.BASE64_FILESIZE, fileSize);
                        bundle.putInt(Constant.BASE64_CODE, 2);
                        msg.obj = bundle;
                        msg.sendToTarget();
                    } else {
                        Log.e("wifiStatus", NetworkUtils.isAvailable(context) + "");
                        //判断是否有网络，如果没有则直接离线上传
                        if (NetworkUtils.isAvailable(context)) {
                            //判断用户是否为仅wifi情况下上传图片,如果不是wifi则视为离线上传
                            boolean wifi_up = sharedPrefs.getBoolean(Constant.WIFI_UP, false);
                            if (wifi_up) {
                                if (!NetworkUtils.isWifi(context)) {
                                    //图片保存到数据库，有wifi时候在上传
                                    uploadImgForClientOnError(2, path);
                                } else {
                                    //上传图片到客户端
                                    sendUploadToHandler(path);
                                }
                            } else {
                                //上传图片到客户端
                                sendUploadToHandler(path);
                            }
                        } else {
                            uploadImgForClientOnError(2, path);
                        }
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                    //如果没有图片的话隐藏dialog
                    handler.sendEmptyMessage(HIDE_DIALOG);
                }
            }
        }).start();
    }

    //给上传到客户端发送handler
    private void sendUploadToHandler(String imagName) {
        try {
            //图片路径
            String imagePath = ImageUtils.getH5ImagePath(imagName, this);
            Message msg = handler.obtainMessage(TAKEPIC_UPLOAD);
            Bundle mBundle = new Bundle();
            mBundle.putString("imagePath", imagePath);
            mBundle.putString(Constant.UPLOAD_IAMGE_NAME, imagName);
            msg.setData(mBundle);
            msg.sendToTarget();
        } catch (Exception e) {
            e.printStackTrace();
        }

    }

    @Override
    protected H5Presenter createPresenter() {
        return new H5Presenter();
    }

    long mCurTime;
    long mLastTime;

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK) {
            if (Constant.isBao) {
                KLog.e(1111);
                backNativeLastPage();
            } else {
                if (MotionEvent.ACTION_DOWN == event.getAction()) {
                    boolean isSdk = sharedPrefs.getBoolean(Constant.IS_SDK, false);
                    if (isSdk) {
                        handler.sendEmptyMessage(ONE_CLICK);
                    } else {
                        mLastTime = mCurTime;
                        mCurTime = System.currentTimeMillis();
                        if (mCurTime - mLastTime < 1000) {//双击事件
                            mCurTime = 0;
                            mLastTime = 0;
                            handler.removeMessages(ONE_CLICK);
                            handler.sendEmptyMessage(DOUBLE_CLICK);
                        } else {//单击事件
                            handler.sendEmptyMessageDelayed(ONE_CLICK, 310);
                        }
                    }
                }
                return true;
            }
        }
        return false;
    }


    // 退出
    private void exit() {
        hideLoading();
        AlertDialog.Builder builder = new AlertDialog.Builder(H5Activity.this);
        builder.setTitle(R.string.remind);
        builder.setMessage(R.string.dialog_suretoexit);
        builder.setPositiveButton(android.R.string.ok,
                new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        handler.sendEmptyMessage(ONKEYDOWN_SUCCESS);
                        finish();

                    }
                });
        builder.setNegativeButton(android.R.string.cancel, null);
        builder.show();
    }


    //避免多次广播
    private static int lastType = -1;
    /**
     * 网络监听广播,再有问题换CONNECTIVITY_SERVICE getActiveNetworkInfo试试
     */
    private BroadcastReceiver mConnectivityChanged = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            try {
//                NetworkInfo info = (NetworkInfo) intent.getParcelableExtra(ConnectivityManager.EXTRA_NETWORK_INFO);
//                boolean hasConnectivity = (info != null && info.isConnected()) ? true : false;
//                int netType = info.getType();
//                String subtypeName = info.getTypeName();
//                if (subtypeName.equals("WIFI")) {
//                    connectType = "WIFI";
//                } else {
//                    connectType = "MOBILE";
//                }
//                if (networkMode.equals("1")) {
//                    return;
//                }
//                if (hasConnectivity) {
//                    //避免第二次相同广播
//                    if (lastType == netType) {
//                        return;
//                    }
//                    //保存本次网络状态
//                    lastType = netType;
//                    if (!isConnect) {
//                        handler.sendEmptyMessage(NETWORK_ONLINE);
//                        XLog.i("NETWORK_ONLINE网络" + isConnect);
//                    }
//                } else {
//                    handler.sendEmptyMessage(NETWORK_OFFLINE);
//                    XLog.i("NETWORK_OFFLINE网络" + isConnect);
//                    lastType = -1;
//                    isConnect = false;
//                }

                // 检查是否有网络连接
                ConnectivityManager connMgr = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
                NetworkInfo networkInfo = connMgr.getActiveNetworkInfo();
                if (networkInfo != null && networkInfo.isConnected()) {
                    // 网络连接
                    Log.i("NetworkChangeReceiver", "网络已连接");
                    handler.sendEmptyMessage(NETWORK_ONLINE);
                } else {
                    // 网络断开
                    Log.i("NetworkChangeReceiver", "网络已断开");
                    handler.sendEmptyMessage(NETWORK_OFFLINE);
                    Log.e("huohuohuohuo", "112277");
                }
            } catch (Exception e) {
            }
        }
    };


    @Override
    protected void onDestroy() {
        super.onDestroy();
        KLog.e("H5onDestory");
        // clearX5Cache();
        hideLoading();
        //取消广播
        if (mConnectivityChanged != null) {
            if (mReceiverConnectTag) {
                mReceiverConnectTag = false;
                unregisterReceiver(mConnectivityChanged);

            }
        }
        if (wifiConnectivityChanged != null) {
            if (mReceiverWIfiConnectTag) {
                mReceiverWIfiConnectTag = false;
                unregisterReceiver(wifiConnectivityChanged);
            }
        }
        if (myPhoneListener != null && telephonyManager != null) {
            telephonyManager.listen(myPhoneListener, PhoneStateListener.LISTEN_NONE);
            myPhoneListener = null;
            telephonyManager = null;
        }
        if (uploadImageIntent != null) {
            stopService(uploadImageIntent);
        }
        // if (foregroundIntent!=null) {
        //   stopService(foregroundIntent);
        //}
        if (isGPSOpen) {
            if (gpsIntent != null) {
                stopService(gpsIntent);
            }
        }
        if (wakeLock != null) {
            wakeLock.release();
            wakeLock = null;
        }
        // getAppManager().finishAllActivity();
    }

    //监听移动数据4g,3g等
    public void getPhoneState(Context context) {
        telephonyManager = (TelephonyManager) context.getSystemService(Context.TELEPHONY_SERVICE);
        //系统自带的服务监听器，实时监听网络状态
        myPhoneListener = new PhoneStateListener() {
            //系统自带的服务监听器，实时监听网络状态
            @Override
            public void onServiceStateChanged(ServiceState serviceState) {
                super.onServiceStateChanged(serviceState);
            }

            @Override
            public void onSignalStrengthsChanged(SignalStrength signalStrength) {

                try {
                    Method levelMethod = SignalStrength.class.getDeclaredMethod("getLevel");

                    signalLevel = (int) levelMethod.invoke(signalStrength);
//                    Toast.makeText(getApplicationContext(),signalLevel+ "当前网络不给力，转入离线操作", Toast.LENGTH_LONG).show();
                } catch (IllegalAccessException e) {
                    e.printStackTrace();
                } catch (InvocationTargetException e) {
                    e.printStackTrace();
                } catch (NoSuchMethodException e) {
                    e.printStackTrace();
                }

                //这个dbm 是2G和3G信号的值
                asu = signalStrength.getGsmSignalStrength();
                gprsDbm = -113 + 2 * asu;
                getNetworkState();
                super.onSignalStrengthsChanged(signalStrength);
            }
        };
        telephonyManager.listen(myPhoneListener, PhoneStateListener.LISTEN_SIGNAL_STRENGTHS);
    }

    //监听wifi
    private BroadcastReceiver wifiConnectivityChanged = new BroadcastReceiver() {
        private Context mContext;

        @Override
        public void onReceive(Context context, Intent intent) {
            mContext = context;
            getWifiInfo();
        }

        private void getWifiInfo() {
            WifiManager wifiManager = (WifiManager) mContext.getSystemService(mContext.WIFI_SERVICE);
            WifiInfo wifiInfo = wifiManager.getConnectionInfo();

            if (wifiInfo.getBSSID() != null) {
                //wifi名称
                wifilevel = wifiInfo.getRssi();
                wifiStrength = WifiManager.calculateSignalLevel(wifiInfo.getRssi(), 4);
                getNetworkState();
            }
        }
    };

    public void getNetworkState() {
        if (networkMode.equals("1")) {
            return;
        }
    }

    private void receiveNfcResult() {
        RxBus.getDefault().toObservable(NFCResult.class).subscribe(new RxBusSubscriber<NFCResult>() {
            @Override
            public void receive(NFCResult data) {

                if (data.isScanToOpenNfc()) {
                    Message msg = handler.obtainMessage(SCAN_SUCCESS);
                    msg.obj = data.getCode();
                    msg.sendToTarget();
                } else {
                    Message msg = handler.obtainMessage(NFC_SUCCESS);
                    msg.obj = data.getCode();
                    msg.sendToTarget();
                }

            }
        });


        RxBus.getDefault().toObservable(NotificationSound.class)
                .compose(this.<NotificationSound>bindToLifecycle())
                .subscribe(new RxBusSubscriber<NotificationSound>() {
                    @Override
                    public void receive(NotificationSound data) {
                        String extras = data.getExtras();
                        playSound(extras);
                    }
                });

        RxBus.getDefault().toObservable(RecordError.class).subscribe(new RxBusSubscriber<RecordError>() {
            @Override
            public void receive(RecordError data) {
                ToastMessage(context.getResources().getString(R.string.record_error));
                getAppManager().finishActivity(RecordVideoActivity.class);
            }
        });


        RxBus.getDefault().toObservable(NotificationUpdateTaskList.class)
                .compose(this.<NotificationUpdateTaskList>bindToLifecycle())
                .subscribe(new RxBusSubscriber<NotificationUpdateTaskList>() {
                    @Override
                    public void receive(NotificationUpdateTaskList data) {
                        XLog.i("刷新任务列表");
                        Message msg = handler.obtainMessage(UPDATE_TASK_LIST);
                        msg.obj = data.getExtras();
                        msg.sendToTarget();
                    }
                });

        RxBus.getDefault().toObservable(OpenMessageEvent.class)
                .compose(this.<OpenMessageEvent>bindToLifecycle())
                .subscribe(new RxBusSubscriber<OpenMessageEvent>() {
                    @Override
                    public void receive(OpenMessageEvent data) {
                        XLog.i("打开通知的消息");
                        if (webView != null) {
                            webView.clearView();
                            XLog.i("data.getExtras()=" + data.getExtras());
//                            if (data.getExtras().contains("/h5/mytask")){
                            webView.loadUrl(data.getExtras());
                            bringAppToForeground();

//                            }

                        }
                    }
                });
    }


    List<String> permissionLists10 = new ArrayList<>();
    List<String> permissionLists11 = new ArrayList<>();
    List<String> permissionLists12 = new ArrayList<>();
    List<String> permissionLists13 = new ArrayList<>();

    private void applyPermissions() {

        if (Build.VERSION.SDK_INT >= 23) {
            permissionLists10.clear();
            permissionLists11.clear();
            permissionLists12.clear();
            permissionLists13.clear();
            //1.拍摄照片和录制内容
            //2。访问您设备上的照片。媒体文件内容和文件
            //3。录制视频
            //
            if (ContextCompat.checkSelfPermission(this, Manifest.permission.CAMERA) != PackageManager.PERMISSION_GRANTED) {
                permissionLists10.add(Manifest.permission.CAMERA);
            }


            if (ContextCompat.checkSelfPermission(this, Manifest.permission.RECORD_AUDIO) != PackageManager.PERMISSION_GRANTED) {
                permissionLists11.add(Manifest.permission.RECORD_AUDIO);
            }


            if (ContextCompat.checkSelfPermission(H5Activity.this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
                permissionLists12.add(Manifest.permission.ACCESS_FINE_LOCATION);
            }
            if (ContextCompat.checkSelfPermission(H5Activity.this, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
                permissionLists12.add(Manifest.permission.ACCESS_COARSE_LOCATION);
            }
//            if (ContextCompat.checkSelfPermission(H5Activity.this, Manifest.permission.FOREGROUND_SERVICE) != PackageManager.PERMISSION_GRANTED) {
//                permissionLists12.add(Manifest.permission.FOREGROUND_SERVICE);
//            }


//            if (ContextCompat.checkSelfPermission(H5Activity.this, Manifest.permission.READ_PHONE_STATE) != PackageManager.PERMISSION_GRANTED) {
//                permissionLists13.add(Manifest.permission.READ_PHONE_STATE);
//            }
            if (ContextCompat.checkSelfPermission(this, Manifest.permission.WRITE_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) {
                permissionLists13.add(Manifest.permission.WRITE_EXTERNAL_STORAGE);
            }
            if (ContextCompat.checkSelfPermission(this, Manifest.permission.READ_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) {
                permissionLists13.add(Manifest.permission.READ_EXTERNAL_STORAGE);
            }

            if (permissionLists10.size() > 0) {
                ActivityCompat.requestPermissions(this, permissionLists10.toArray(new String[permissionLists10.size()]), 10);
                snackbar = SnackBarUtil.show(this, "获取拍摄照片和录制内容的权限说明：", "用于拍照和录制视频");
            } else if (permissionLists11.size() > 0) {
                ActivityCompat.requestPermissions(this, permissionLists11.toArray(new String[permissionLists11.size()]), 11);
                snackbar = SnackBarUtil.show(this, "获取麦克风和录制的权限说明：", "用于录制视频");
            } else if (permissionLists12.size() > 0) {
                ActivityCompat.requestPermissions(this, permissionLists12.toArray(new String[permissionLists12.size()]), 12);
                snackbar = SnackBarUtil.show(this, "获取您地理位置的权限说明：", "用于记录当前的位置");
            } else if (permissionLists13.size() > 0) {//说明肯定有拒绝的权限
                ActivityCompat.requestPermissions(this, permissionLists13.toArray(new String[permissionLists13.size()]), 13);
                snackbar = SnackBarUtil.show(this, "获取您设备上的照片.媒体文件内容和文件的权限说明：", "用于储存照片和视频");
            } else {
                nativeTakePhoto();
            }
        }

    }

    private void applyPermissionsScan() {

        if (Build.VERSION.SDK_INT >= 23) {
            List<String> permissionLists = new ArrayList<>();
            if (ContextCompat.checkSelfPermission(this, Manifest.permission.CAMERA) != PackageManager.PERMISSION_GRANTED) {
                permissionLists.add(Manifest.permission.CAMERA);
            }

            if (permissionLists.size() > 0) {//说明肯定有拒绝的权限
                ActivityCompat.requestPermissions(this, permissionLists.toArray(new String[permissionLists.size()]), 4);
                snackbar = SnackBarUtil.show(this, "获取相机权限说明：", "用于扫描位置码或者设备码");
            } else {
                Log.e("222", "1222211");
                Intent intent = new Intent(context, CaptureActivity.class);
                intent.putExtra("bletooth", "1");
                startActivityForResult(intent, SCAN_CODE);
            }

        }

    }


    @Override
    public void onRequestPermissionsResult(int requestCode, String permissions[],
                                           int[] grantResults) {
        switch (requestCode) {

            case 1:
                if (snackbar != null) {
                    snackbar.dismiss();
                }
                if (grantResults.length > 0) {
                    for (int grantResult : grantResults) {
                        if (grantResult != PackageManager.PERMISSION_GRANTED) {
                            ToastMessage(getResources().getString(R.string.please_set_paizhao_per));  //权限被拒绝将无法调用相机
                            return;
                        }
                    }
                    //其他逻辑(这里当权限都同意的话就执行打电话逻辑)
//                    nativeTakePhoto();
                }

                if (permissionLists2.size() > 0) {
                    ActivityCompat.requestPermissions(this, permissionLists2.toArray(new String[permissionLists2.size()]), 5);
                    snackbar = SnackBarUtil.show(this, "获取麦克风和录制的权限说明：", "用于录制视频");
                } else if (permissionLists3.size() > 0) {
                    ActivityCompat.requestPermissions(this, permissionLists3.toArray(new String[permissionLists3.size()]), 6);
                    snackbar = SnackBarUtil.show(this, "获取您设备上的照片.媒体文件内容和文件的权限说明：", "用于储存照片和视频");
                } else if (permissionLists4.size() > 0) {
                    ActivityCompat.requestPermissions(this, permissionLists4.toArray(new String[permissionLists4.size()]), 7);
                    snackbar = SnackBarUtil.show(this, "获取您地理位置的权限说明：", "用于记录当前的位置");
                }

                break;
            case 3: //申请位置权限
                if (snackbar != null) {
                    snackbar.dismiss();
                }
                if (grantResults.length > 0) {
                    for (int grantResult : grantResults) {
                        if (grantResult != PackageManager.PERMISSION_GRANTED) {
                            ToastMessage(getResources().getString(R.string.please_set_location_per));  //权限被拒绝将无法调用相机
                            return;
                        }
                    }
                }
                if (mLocationType == 0) {
                    initLocation();
                } else {
                    initShiahiLocation();
                }
                break;
            case 4:
                if (snackbar != null) {
                    snackbar.dismiss();
                }
                if (grantResults.length > 0) {
                    for (int grantResult : grantResults) {
                        if (grantResult != PackageManager.PERMISSION_GRANTED) {
                            ToastMessage(getResources().getString(R.string.please_set_scan_per));  //权限被拒绝将无法调用相机
                            return;
                        }
                    }
                    //其他逻辑(这里当权限都同意的话就执行打电话逻辑)
//                    nativeTakePhoto();
                }
                break;
            case 5:
                if (snackbar != null) {
                    snackbar.dismiss();
                }
                if (grantResults.length > 0) {
                    for (int grantResult : grantResults) {
                        if (grantResult != PackageManager.PERMISSION_GRANTED) {
                            ToastMessage(getResources().getString(R.string.please_set_paizhao_per));  //权限被拒绝将无法调用相机
                            return;
                        }
                    }
                }
                if (permissionLists3.size() > 0) {
                    ActivityCompat.requestPermissions(this, permissionLists3.toArray(new String[permissionLists3.size()]), 6);
                    snackbar = SnackBarUtil.show(this, "获取您设备上的照片.媒体文件内容和文件的权限说明：", "用于储存照片和视频");
                } else if (permissionLists4.size() > 0) {
                    ActivityCompat.requestPermissions(this, permissionLists4.toArray(new String[permissionLists4.size()]), 7);
                    snackbar = SnackBarUtil.show(this, "获取您地理位置的权限说明：", "用于记录当前的位置");
                }
                break;
            case 6:
                if (snackbar != null) {
                    snackbar.dismiss();
                }
                if (grantResults.length > 0) {
                    for (int grantResult : grantResults) {
                        if (grantResult != PackageManager.PERMISSION_GRANTED) {
                            ToastMessage(getResources().getString(R.string.please_set_paizhao_per));  //权限被拒绝将无法调用相机
                            return;
                        }
                    }
                }

                if (permissionLists4.size() > 0) {
                    ActivityCompat.requestPermissions(this, permissionLists4.toArray(new String[permissionLists4.size()]), 7);
                    snackbar = SnackBarUtil.show(this, "获取您地理位置的权限说明：", "用于记录当前的位置");
                }
                break;

            case 7:
                if (snackbar != null) {
                    snackbar.dismiss();
                }
                if (grantResults.length > 0) {
                    for (int grantResult : grantResults) {
                        if (grantResult != PackageManager.PERMISSION_GRANTED) {
                            ToastMessage(getResources().getString(R.string.please_set_paizhao_per));  //权限被拒绝将无法调用相机
                            return;
                        }
                    }
                }
                break;

            case 10:
                if (snackbar != null) {
                    snackbar.dismiss();
                }
                if (grantResults.length > 0) {
                    for (int grantResult : grantResults) {
                        if (grantResult != PackageManager.PERMISSION_GRANTED) {
                            ToastMessage(getResources().getString(R.string.please_set_paizhao_per));  //权限被拒绝将无法调用相机
                            return;
                        }
                    }
                }
                if (permissionLists11.size() > 0) {
                    ActivityCompat.requestPermissions(this, permissionLists11.toArray(new String[permissionLists11.size()]), 11);
                    snackbar = SnackBarUtil.show(this, "获取麦克风和录制的权限说明：", "用于录制视频");
                } else if (permissionLists12.size() > 0) {
                    ActivityCompat.requestPermissions(this, permissionLists12.toArray(new String[permissionLists12.size()]), 12);
                    snackbar = SnackBarUtil.show(this, "获取您地理位置的权限说明：", "用于记录当前的位置");
                } else if (permissionLists13.size() > 0) {//说明肯定有拒绝的权限
                    ActivityCompat.requestPermissions(this, permissionLists13.toArray(new String[permissionLists13.size()]), 13);
                    snackbar = SnackBarUtil.show(this, "获取您设备上的照片.媒体文件内容和文件的权限说明：", "用于储存照片和视频");
                }
                break;
            case 11:
                if (snackbar != null) {
                    snackbar.dismiss();
                }
                if (grantResults.length > 0) {
                    for (int grantResult : grantResults) {
                        if (grantResult != PackageManager.PERMISSION_GRANTED) {
                            ToastMessage(getResources().getString(R.string.please_set_paizhao_per));  //权限被拒绝将无法调用相机
                            return;
                        }
                    }
                }

                if (permissionLists12.size() > 0) {
                    ActivityCompat.requestPermissions(this, permissionLists12.toArray(new String[permissionLists12.size()]), 12);
                    snackbar = SnackBarUtil.show(this, "获取您地理位置的权限说明：", "用于记录当前的位置");
                } else if (permissionLists13.size() > 0) {//说明肯定有拒绝的权限
                    ActivityCompat.requestPermissions(this, permissionLists13.toArray(new String[permissionLists13.size()]), 13);
                    snackbar = SnackBarUtil.show(this, "获取您设备上的照片.媒体文件内容和文件的权限说明：", "用于储存照片和视频");
                }
                break;
            case 12:
                if (snackbar != null) {
                    snackbar.dismiss();
                }
                if (grantResults.length > 0) {
                    for (int grantResult : grantResults) {
                        if (grantResult != PackageManager.PERMISSION_GRANTED) {
                            ToastMessage(getResources().getString(R.string.please_set_paizhao_per));  //权限被拒绝将无法调用相机
                            return;
                        }
                    }
                }

                if (permissionLists13.size() > 0) {//说明肯定有拒绝的权限
                    ActivityCompat.requestPermissions(this, permissionLists13.toArray(new String[permissionLists13.size()]), 13);
                    snackbar = SnackBarUtil.show(this, "获取您设备上的照片.媒体文件内容和文件的权限说明：", "用于储存照片和视频");
                }
                break;
            case 13:
                if (snackbar != null) {
                    snackbar.dismiss();
                }
                if (grantResults.length > 0) {
                    for (int grantResult : grantResults) {
                        if (grantResult != PackageManager.PERMISSION_GRANTED) {
                            ToastMessage(getResources().getString(R.string.please_set_paizhao_per));  //权限被拒绝将无法调用相机
                            return;
                        }
                    }
                }

                break;
            default:
                break;
        }
    }


    public void findview() {
        webFramlayout = (FrameLayout) findViewById(R.id.web_framlayout);
        titlebar = (TitleBar) findViewById(R.id.titlebar);
        llSearch = (LinearLayout) findViewById(R.id.ll_search);
        edittextSearch = (EditText) findViewById(R.id.edittext_search);
        btSearch = (Button) findViewById(R.id.bt_search);

    }

    @Override
    public void isBackground(int backgroundType) {
        Message msg = handler.obtainMessage(IS_BACKGROUND);
        msg.obj = backgroundType;
        msg.sendToTarget();
    }


    private void getGps() {

        String addr = PreferencesHelper.getData(Constant.LON_LAT_DESC_ADDR);
        if (!TextUtils.isEmpty(addr)) {
            String[] addrArray = addr.split("timestamp=");
            String timeStr = addrArray[1];
            if (System.currentTimeMillis() - Long.parseLong(timeStr) > 10 * 60 * 1000) {
                checkLocationPermission(0);
                XLog.i("定位：" + "大于十分钟");
            } else {
                XLog.i("定位：" + "小于十分钟");
                if (TextUtils.isEmpty(addrArray[0]) || "null".equals(addrArray[0])) {
                    checkLocationPermission(0);
                } else {
                    locationDescribe = addrArray[0];
                }

            }

        } else {
            checkLocationPermission(0);
        }


    }

    private void initShiahiLocation() {
        LocationClient.setAgreePrivacy(true);
        if (mLocationClient_shishi == null) {
            try {
                mLocationClient_shishi = new LocationClient(getApplicationContext());
                //声明LocationClient类
                mLocationClient_shishi.registerLocationListener(mListeners_shishi);
                LocationClientOption option = new LocationClientOption();
                //定位模式，目前为网络定位
                option.setLocationMode(LocationClientOption.LocationMode.Hight_Accuracy);
                option.setOpenGps(true);// 打开gps
                option.setCoorType("bd09ll"); // 设置坐标类型
                option.setAddrType("all");
                //指定的时间定位一次
                option.setScanSpan(0);
                option.setIsNeedLocationDescribe(true);
                mLocationClient_shishi.setLocOption(option);
                Log.e("shuchang", "mLocationClient_shishi开启定位----->");
                mLocationClient_shishi.start();
            } catch (Exception e) {
                e.printStackTrace();
            }

        } else {
            mLocationClient_shishi.start();
        }

    }

    private BDAbstractLocationListener mListeners_shishi = new BDAbstractLocationListener() {

        @Override
        public void onReceiveLocation(BDLocation location) {
            Log.e("shuchang", "--->BDLocationListener-->loctype= " + location.getLocType());
            XLog.i(location.toString() + ":=-=-getCurrentTimeLongAndLat=-=H-");
            // TODO Auto-generated method stub

            Message tempMsg = mHandler.obtainMessage();
            tempMsg.what = GET_SHISHI_LOCATION_SUCCESS;

            if (null != location && location.getLocType() != BDLocation.TypeServerError) {
                locationDescribe = location.getAddress().address;
                if (TextUtils.isEmpty(locationDescribe) || "null".equals(locationDescribe)) {
                    locationDescribe = location.getAddrStr();
                }
                bean.Position = locationDescribe;
                if (location.getLongitude() == 0 || (location.getLongitude() + "").equals("0.0000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000049")) {
                    bean.sLon = String.valueOf(0);
                    bean.sLat = String.valueOf(0);
                    bean.Position = "0";
                    Log.e("shuchang", "--->错误定位-->" + "经纬度错误：" + location.getLatitude() + "--" + location.getLongitude() + "--" + location.getTime());
                } else {
                    if ("4.9E-324".equals(String.valueOf(location.getLongitude()))) {
                        bean.sLon = String.valueOf(0);
                        bean.sLat = String.valueOf(0);
                    } else {
                        bean.sLon = String.valueOf(location.getLongitude());
                        bean.sLat = String.valueOf(location.getLatitude());
                    }
                    Log.e("shuchang", "--->中海定位-->" + Double.toString(location.getLatitude()) + "--" + Double.toString(location.getLongitude()) + "--!@");
                }

//                tempMsg.obj = gson.toJson(bean);
                getGeoAddress(bean, tempMsg);
//                handler.sendMessage(tempMsg);

            } else {
                bean.sLon = String.valueOf(0);
                bean.sLat = String.valueOf(0);
                bean.Position = "0";
                sharedPrefs.edit().putString(Constant.LON_SHISHI_LAT_DESC, gson.toJson(bean)).apply();
                Log.e("shuchang", "--->错误定位-->" + "经纬度错误：" + location.getLatitude() + "--" + location.getLongitude() + "--" + location.getTime());
//                ToastMgr.show("定位失败，请打开GPS或者检查网络");
                Log.e("LocationService", "定位失败，请打开GPS或者检查网络");
//                tempMsg.obj = gson.toJson(bean);
//                handler.sendMessage(tempMsg);
                getGeoAddress(bean, tempMsg);
            }
        }

    };


    private void initLocation() {
        LocationClient.setAgreePrivacy(true);
        if (mLocationClient == null) {
            try {
                mLocationClient = new LocationClient(getApplicationContext());
                //声明LocationClient类
                mLocationClient.registerLocationListener(mListeners);
                LocationClientOption option = new LocationClientOption();
                //定位模式，目前为网络定位
                option.setLocationMode(LocationClientOption.LocationMode.Hight_Accuracy);
                option.setOpenGps(true);// 打开gps
                option.setCoorType("bd09ll"); // 设置坐标类型
                option.setAddrType("all");
                //指定的时间定位一次
                option.setScanSpan(1000);
                mLocationClient.setLocOption(option);
                option.setIsNeedLocationDescribe(true);
                mLocationClient.start();
            } catch (Exception e) {
                e.printStackTrace();
            }
        } else {
            mLocationClient.start();
        }


    }

    public static String locationDescribe;
    private BDAbstractLocationListener mListeners = new BDAbstractLocationListener() {

        @Override
        public void onReceiveLocation(BDLocation location) {
            if (null != location && location.getLocType() != BDLocation.TypeServerError) {
                String ld = location.getAddress().address;
                Log.e("shuchang", "locationDescribe--->" + ld);
                XLog.i("定位：" + Double.toString(location.getLatitude()) + "--" + Double.toString(location.getLongitude()) + "--" + location.getLocType());
                if (!TextUtils.isEmpty(ld) && !"null".equals(ld)) {
                    locationDescribe = ld;

                    getGeoAddressImg(location);
//                    PreferencesHelper.saveData(Constant.LON_LAT_DESC_ADDR, locationDescribe + "timestamp=" + System.currentTimeMillis());
                    mLocationClient.stop();
                }

            } else {
                Log.e("LocationService", "定位失败，请打开GPS或者检查网络");
            }
        }

    };

    private void getGeoAddressImg(BDLocation location) {
        mCoder = GeoCoder.newInstance();
        mLatLng = new LatLng(location.getLatitude(), location.getLongitude());
        mCoder.setOnGetGeoCodeResultListener(new OnGetGeoCoderResultListener() {

            @Override
            public void onGetGeoCodeResult(GeoCodeResult geoCodeResult) {

            }

            @Override
            public void onGetReverseGeoCodeResult(ReverseGeoCodeResult reverseGeoCodeResult) {
                if (reverseGeoCodeResult == null || reverseGeoCodeResult.error != SearchResult.ERRORNO.NO_ERROR) {
                    Log.e("shuchang", "getGeoAddressImg--->reverseGeoCodeResult.error-->" + reverseGeoCodeResult.error);
                    Log.e("shuchang", "getGeoAddressImg--->ReverseGeoCodeResult-->" + new Gson().toJson(reverseGeoCodeResult));
                    //没有找到检索结果
                    return;
                } else {
                    poiList = reverseGeoCodeResult.getPoiList();
                    if (poiList != null && poiList.size() > 0) {
                        if (poiList.size() > 1) {
                            locationDescribe = locationDescribe + poiList.get(1).name + "附近";
                        } else {
                            locationDescribe = locationDescribe + poiList.get(0).name + "附近";
                        }
                    }

                    Log.e("shuchang", "getGeoAddressImg--->" + bean.Position);

//                    //详细地址
//                    String address = reverseGeoCodeResult.getAddress();
//                    //行政区号
//                    int adCode = reverseGeoCodeResult.getAdcode();
//
//                    locationDescribe = address;
                    mCoder.destroy();
                }
            }
        });

        mCoder.reverseGeoCode(new ReverseGeoCodeOption()
                .location(mLatLng)
                // 设置是否返回新数据 默认值0不返回，1返回
                .newVersion(1)
                // POI召回半径，允许设置区间为0-1000米，超过1000米按1000米召回。默认值为1000
                .radius(50));
        mCoder.destroy();
    }

    GeoCoder mCoder;
    LatLng mLatLng;

    private void getGeoAddress(final GPSBean bean, final Message tempMsg) {
        mCoder = GeoCoder.newInstance();
        mLatLng = new LatLng(Double.parseDouble(bean.sLat), Double.parseDouble(bean.sLon));
        mCoder.setOnGetGeoCodeResultListener(new OnGetGeoCoderResultListener() {

            @Override
            public void onGetGeoCodeResult(GeoCodeResult geoCodeResult) {

            }

            @Override
            public void onGetReverseGeoCodeResult(ReverseGeoCodeResult reverseGeoCodeResult) {
                if (reverseGeoCodeResult == null || reverseGeoCodeResult.error != SearchResult.ERRORNO.NO_ERROR) {
                    //没有找到检索结果
                    return;
                } else {
                    //详细地址
                    String address = reverseGeoCodeResult.getAddress();
                    poiList = reverseGeoCodeResult.getPoiList();
                    if (poiList != null && poiList.size() > 0) {
                        if (poiList.size() > 1) {
                            bean.Position = bean.Position + poiList.get(1).name + "附近";
                        } else {
                            bean.Position = bean.Position + poiList.get(0).name + "附近";
                        }
                    }

                    Log.e("shuchang", "getGeoAddress--->" + bean.Position);
                    //行政区号
                    int adCode = reverseGeoCodeResult.getAdcode();

                    tempMsg.obj = gson.toJson(bean);
                    handler.sendMessage(tempMsg);

                    mCoder.destroy();
                }
            }
        });

        mCoder.reverseGeoCode(new ReverseGeoCodeOption()
                .location(mLatLng)
                // 设置是否返回新数据 默认值0不返回，1返回
                .newVersion(1)
                // POI召回半径，允许设置区间为0-1000米，超过1000米按1000米召回。默认值为1000
                .radius(50));
    }

    private void playSound(String extras) {

        SoundUtils.getInstance().playSound(getApplication(), extras);
    }

    private View view_back;

    @Override
    protected void onResume() {
        super.onResume();
//        if (Constant.isBao) {
//            view_back.setVisibility(View.VISIBLE);
//        } else {
//            view_back.setVisibility(View.GONE);
//        }
        if (webView != null) {
            Log.e("shuchang", "h5activity-onresume--->onAppWebviewShow");
            webView.loadUrl("javascript:" + "onAppWebviewShow()");//返回webview页面触发
            webView.loadUrl("javascript:" + "onAppAvatarUpdate()"); //更新头像触发
            if (handler != null) {
                Message msg = handler.obtainMessage(UPDATE_TASK_LIST);
                msg.sendToTarget();
                handler.sendEmptyMessage(987);
            }

        }
    }

    /**
     * 选择相机或者相册
     */
    public void uploadPicture() {

        AlertDialog.Builder builder = new AlertDialog.Builder(this);
        builder.setTitle("请选择图片上传方式");

        //取消对话框
        builder.setOnCancelListener(new DialogInterface.OnCancelListener() {
            @Override
            public void onCancel(DialogInterface dialog) {

                //一定要返回null,否则<input type='file'>
                if (uploadMessage != null) {
                    uploadMessage.onReceiveValue(null);
                    uploadMessage = null;
                }
                if (uploadMessageAboveL != null) {
                    uploadMessageAboveL.onReceiveValue(null);
                    uploadMessageAboveL = null;

                }
            }
        });


        builder.setPositiveButton("相机", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                if (!TextUtils.isEmpty(mLastPhothPath)) {
                    //上一张拍照的图片删除
                    mThread = new Thread(new Runnable() {
                        @Override
                        public void run() {
                            File file = new File(mLastPhothPath);
                            if (file != null) {
                                file.delete();
                            }
                            mHandler.sendEmptyMessage(1);
                        }
                    });
                    mThread.start();
                } else {
                    //请求拍照权限
                    if (ActivityCompat.checkSelfPermission(H5Activity.this, Manifest.permission.CAMERA) == PackageManager.PERMISSION_GRANTED) {
                        takePhoto();
                    } else {
                        ActivityCompat.requestPermissions(H5Activity.this, new String[]{Manifest.permission.CAMERA}, REQUEST_CODE_PERMISSION_CAMERA);
                        snackbar = SnackBarUtil.show(H5Activity.this, "获取相机权限说明：", "用于拍照");
                    }
                }
            }
        });
        builder.setNegativeButton("相册", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                chooseAlbumPic();
            }
        });

        builder.create().show();

    }


    private String mCurrentPhotoPath;
    private String mLastPhothPath;
    private Thread mThread;
    private static final int REQUEST_CODE_ALBUM = 0x01;
    private static final int REQUEST_CODE_CAMERA = 0x02;
    private static final int REQUEST_CODE_PERMISSION_CAMERA = 0x03;

    /**
     * 拍照
     */
    private void takePhoto() {

        StringBuilder fileName = new StringBuilder();
        Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);

        fileName.append(UUID.randomUUID()).append("_upload.png");
        File tempFile = new File(getExternalFilesDir(Environment.DIRECTORY_PICTURES), fileName.toString());
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
            intent.setFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
            Uri uri = FileProvider.getUriForFile(this, getApplication().getPackageName() + ".fileprovider", tempFile);
            intent.putExtra(MediaStore.EXTRA_OUTPUT, uri);
        } else {
            Uri uri = Uri.fromFile(tempFile);
            intent.putExtra(MediaStore.EXTRA_OUTPUT, uri);
        }

        mCurrentPhotoPath = tempFile.getAbsolutePath();
        startActivityForResult(intent, REQUEST_CODE_CAMERA);


    }

    /**
     * 选择相册照片
     */
    private void chooseAlbumPic() {
        Intent i = new Intent(Intent.ACTION_GET_CONTENT);
        i.addCategory(Intent.CATEGORY_OPENABLE);
        i.setType("image/*");
        i.putExtra(Intent.EXTRA_ALLOW_MULTIPLE, true);
        startActivityForResult(Intent.createChooser(i, "Image Chooser"), REQUEST_CODE_ALBUM); //Intent.createChooser(i, "Image Chooser")

    }


    @SuppressLint("HandlerLeak")
    Handler mHandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            takePhoto();
        }
    };

    public void bringAppToForeground() {
        ActivityManager am = (ActivityManager) getSystemService(Context.ACTIVITY_SERVICE);
        if (android.os.Build.VERSION.SDK_INT > android.os.Build.VERSION_CODES.LOLLIPOP) {
            // For Android 5.0 and above
            List<ActivityManager.AppTask> tasks = am.getAppTasks();
            if (!tasks.isEmpty()) {
                tasks.get(0).moveToFront();
            }
        } else {
            // For older versions of Android
            am.moveTaskToFront(getTaskId(), ActivityManager.MOVE_TASK_WITH_HOME);
        }
    }

    /**
     * @param locationType 0:initLocation  1:initShiahiLocation
     */
    private int mLocationType = 0;

    private void checkLocationPermission(int locationType) {
        mLocationType = locationType;
        if (Build.VERSION.SDK_INT >= 23) {
            List<String> permissionLists = new ArrayList<>();
            if (ContextCompat.checkSelfPermission(H5Activity.this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
                permissionLists.add(Manifest.permission.ACCESS_FINE_LOCATION);
            }
            if (ContextCompat.checkSelfPermission(H5Activity.this, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
                permissionLists.add(Manifest.permission.ACCESS_COARSE_LOCATION);
            }

            if (permissionLists.size() > 0) {//说明肯定有拒绝的权限
                ActivityCompat.requestPermissions(this, permissionLists.toArray(new String[permissionLists.size()]), 3);
                snackbar = SnackBarUtil.show(this, "获取定位的权限说明：", "用于定位当前地址");
            } else {
                if (locationType == 0) {
                    initLocation();
                } else {
                    initShiahiLocation();
                }
            }

        }
    }

    private long exitTime = 0;
    private int REQUEST_SELECT_IMAGES_CODE = 0x01;

    /**
     * 打开相册
     */
    public void openAblum(int querytype) {
        ConfigManager.QUERY_URI = querytype;
//        Glide.with(getApplicationContext()).clear();

        ImagePicker.getInstance()
                .setTitle(querytype == 0 ? getResources().getString(R.string.image_media)
                        : getResources().getString(R.string.vedio_media))
//                .showImage(true)//设置是否展示图片
//                .showVideo(true)//设置是否展示视频
                .setMaxCount(canSelectNum)//设置最大选择图片数目(默认为9，1是单选)
                .setImageLoader(new GlideLoader())
                .start(this, REQUEST_SELECT_IMAGES_CODE);
    }


    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onMessageEvent(HandleJsEvent event) {
        if (handler != null) {
            Message message = new Message();
            message.what = event.getStatus();
            message.obj = event;
            handler.sendMessage(message);
            // handler.sendEmptyMessage(event.getStatus());//上传一个文件 startUploadFile
        }
    }


//    private boolean netWorkStatus;
//
//    @Subscribe(threadMode = ThreadMode.MAIN)
//    public void onMessageEvent(NetWorkEvent event) {
//        if (event.getNetWork() == 0) {
//            if (netWorkStatus) {
//                handler.sendEmptyMessage(NETWORK_OFFLINE);
//            }
//            netWorkStatus = false;
//        } else {
//            if (!netWorkStatus) {
//                handler.sendEmptyMessage(NETWORK_ONLINE);
//            }
//            netWorkStatus = true;
//        }
//    }


    public void setWebcarch() {
        WebSettings webSetting = webView.getSettings();
        if (NetworkUtils.isAvailable(context)) {
            webSetting.setCacheMode(WebSettings.LOAD_NO_CACHE);
        } else {
            webSetting.setCacheMode(WebSettings.LOAD_CACHE_ELSE_NETWORK);
            XLog.i("WebSettings.LOAD_CACHE_ELSE_NETWORK");
        }
    }

    @Override
    public void getInspOffineUploadTask() {
        handler.sendEmptyMessage(987);
    }

    @Override
    public void changeInspectionState(String json) {
        Message message = handler.obtainMessage(CHANGE_INSPECTION_STATE);
        message.obj = json;
        handler.sendMessage(message);
    }


    @Override
    public void getNativeFileData(String id) {
        if (TextUtils.isEmpty(id)) return;
        KLog.e(id);
        NoNetImageBean bean1 = GsonUtil.GsonToBean(id, NoNetImageBean.class);
        if (bean1 == null || TextUtils.isEmpty(bean1.getUrl())) return;
        String base64 = FileUtil.imageToBase64(bean1.getUrl());
        String uploadNoNet = bean1.getBackFunc();
        Message message = new Message();
        UploadHandlerBean uploadHandlerBean = new UploadHandlerBean(base64, uploadNoNet);
        message.obj = uploadHandlerBean;
        message.what = 998;
        handler.sendMessage(message);
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onMessageEvent(BaoTipEvent event) {
        if (webView != null) {
            ll_loading.setVisibility(View.VISIBLE);
            runOnUiThread(new Runnable() {
                @Override
                public void run() {
                    webView.loadUrl(event.getUrl());
                    //webView.reload();
                }
            });


        }
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onMessageEvent(HomeH5Event event) {
        if (webView != null) {
            webView.loadUrl(Constant.H5ActivityUrl);
        }
    }

    @Override
    public void getResult(DDTypeBean bean) {
        databaseManager.upsertJson("CheckDetailsActivityresult", GsonUtil.BeanToJson(bean));
    }


    private int getImageNum(List<CaUploadImage> list) {
        int num = 0;
        for (int i = 0; i < list.size(); i++) {
            num = num + list.get(i).getImageList().size();
        }
        return num;
    }


    private int getSubmitNum(String listId) {
        List<SubMitPointBean> list = CacheHelper.getInstance().getSubmitPoint();
        KLog.e(GsonUtil.BeanToJson(list));
        int num = 0;
        for (int i = 0; i < list.size(); i++) {
            if (TextUtils.equals(listId, list.get(i).getListId())) {
                num = num + 1;
            }
        }
        KLog.e(num);
        return num;
    }

    @Override
    public void getHistory(WorkHistoryBean bean, String id, String projId) {
        webView.loadUrl("javascript:" + downLoadInspectionCallBack + "('" + 3 + "')");
        new DatabaseManager(context).upsertJson("OperationHistoryActivity" + id + projId, GsonUtil.BeanToJson(bean));
    }
}
